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

前端 未结 4 1260
迷失自我
迷失自我 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:43

    You can generate zero values using the "number" function. Then join your query and zero values using UNION ALL and already according to the obtained data we make a GROUP BY.

    So, your query will look like:

    SELECT SUM(metric),
           time
      FROM (
            SELECT toStartOfQuarter(toDate(1514761200+number*30*24*3600))  time,
                   toUInt16(0) AS metric
              FROM numbers(30)
    
         UNION ALL 
    
              SELECT toStartOfQuarter(created_at) AS time,
                   metric
              FROM mytable
             WHERE created_at >= toDate(1514761200)
               AND created_at >= toDateTime(1514761200)
               AND created_at <= toDate(1546210800)
               AND created_at <= toDateTime(1546210800)
           )
     GROUP BY time
     ORDER BY time
    

    note toUInt16(0) - zero values must be of the same type as metrics

提交回复
热议问题