How to group by time bucket in ClickHouse and fill missing data with nulls/0s

前端 未结 4 1291
迷失自我
迷失自我 2021-01-12 04:15

Suppose I have a given time range. For explanation, let\'s consider something simple, like whole year 2018. I want to query data from ClickHouse as a sum aggregation for eac

4条回答
  •  自闭症患者
    2021-01-12 04:51

    From ClickHouse 19.14 you can use the WITH FILL clause. It can fill quarters in this way:

    WITH
        (
            SELECT toRelativeQuarterNum(toDate('1970-01-01'))
        ) AS init
    SELECT
        -- build the date from the relative quarter number
        toDate('1970-01-01') + toIntervalQuarter(q - init) AS time,
        metric
    FROM
    (
        SELECT
            toRelativeQuarterNum(created_at) AS q,
            sum(rand()) AS metric
        FROM
        (
            -- generate some dates and metrics values with gaps
            SELECT toDate(arrayJoin(range(1514761200, 1546210800, ((60 * 60) * 24) * 180))) AS created_at
        )
        GROUP BY q
        ORDER BY q ASC WITH FILL FROM toRelativeQuarterNum(toDate(1514761200)) TO toRelativeQuarterNum(toDate(1546210800)) STEP 1
    )
    
    ┌───────time─┬─────metric─┐
    │ 2018-01-01 │ 2950782089 │
    │ 2018-04-01 │ 2972073797 │
    │ 2018-07-01 │          0 │
    │ 2018-10-01 │  179581958 │
    └────────────┴────────────┘
    

提交回复
热议问题