【问题标题】:How to get the maximum value below the selected date?如何获得低于所选日期的最大值?
【发布时间】:2019-11-13 18:00:37
【问题描述】:

我有数据集:

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

【问题讨论】:

  • 窗口函数很容易实现,但 ClickHouse 尚不支持它们。

标签: clickhouse


【解决方案1】:

试试这个查询:

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 │
└────────────┴──────────┘
*/

【讨论】:

  • 弗拉基米尔,谢谢。我总是从你的回答中学到新东西。
  • 很高兴为您提供帮助 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多