如何获得低于所选日期的最大值?

3bygqnnd  于 2021-07-15  发布在  ClickHouse
关注(0)|答案(1)|浏览(358)

我有数据集:

date        | used_key
2000-01-01  | 1
2000-01-01  | 2
2000-01-01  | 3
2000-01-01  | 4
2000-01-02  | 1
2000-01-02  | 3
2000-01-03  | 1
2000-01-04  | 5
2000-01-04  | 6
2000-01-06  | 3

我需要获取所选日期之前达到的最大键值:

date        | max_key
2000-01-01  | 4
2000-01-02  | 4
2000-01-03  | 4 
2000-01-04  | 6
2000-01-06  | 6

类似的内容(没有连接部分),但方式正确:

SELECT max(used_key) max_key, date
FROM t1
WHERE 'date_below' <= date
GROUP BY date
dba5bblo

dba5bblo1#

尝试此查询:

SELECT result.1 date, result.2 max_key
FROM (
  SELECT 
    groupArray(date) dates,
    groupArray(max_used_key) max_used_keys,
    arrayMap((date, index) -> (date, arrayReduce('max', arraySlice(max_used_keys, index))), dates, arrayEnumerate(dates)) result_array,
    arrayJoin(result_array) result
  FROM (
    SELECT date, max(used_key) max_used_key
    FROM (
      /* test data */
      SELECT data.1 date, data.2 used_key
      FROM (
        SELECT arrayJoin([
          (toDate('2000-01-01'), 1), 
          (toDate('2000-01-01'), 2), 
          (toDate('2000-01-01'), 3), 
          (toDate('2000-01-01'), 4), 
          (toDate('2000-01-02'), 1), 
          (toDate('2000-01-02'), 3), 
          (toDate('2000-01-03'), 1), 
          (toDate('2000-01-04'), 5), 
          (toDate('2000-01-04'), 6), 
          (toDate('2000-01-06'), 3)]) data)
        )
    GROUP BY date
    ORDER BY date DESC
    )
  );

/* Result:

┌───────date─┬──max_key─┐
│ 2000-01-06 │        6 │
│ 2000-01-04 │        6 │
│ 2000-01-03 │        4 │
│ 2000-01-02 │        4 │
│ 2000-01-01 │        4 │
└────────────┴──────────┘

* /

相关问题