【问题标题】:Group by on clickhouse with condition less than grouped column按条件小于分组列的clickhouse分组
【发布时间】:2021-04-04 14:06:45
【问题描述】:

我有部分sql代码:

select   
    ,inst_date
    ,country
    ,count (distinct (case when (event_day - inst_date) <= 0 then id end)) as event_0
    ,count (distinct (case when (event_day - inst_date) <= 1 then id end)) as event_1
    ,count (distinct (case when (event_day - inst_date) <= 2 then id end)) as event_2
    ,count (distinct (case when (event_day - inst_date) <= 3 then id end)) as event_3
    ,count (distinct (case when (event_day - inst_date) <= 4 then id end)) as event_4
    ,count (distinct (case when (event_day - inst_date) <= 5 then id end)) as event_5
    ,count (distinct (case when (event_day - inst_date) <= 6 then id end)) as event_6
    ,count (distinct (case when (event_day - inst_date) <= 7 then id end)) as event_7
from t1
all left join 
(
    select distinct id
         , toDate(event_date) as event_day
         , 1 as event
    from events
) as events_
using id
where (event_day - inst_date) between 0 and 7
group by inst_date
    ,country ;

我看到了我的数据:

inst_date country event_0 event_1 event_2 event_3 event_4 event_5 event_6 event_7
2020-12-01 us 10 11 11 12 13 14 14 14

但我想像这样收集这些数据

inst_date country date_difference events_count
2020-12-01 us 0 10
2020-12-01 us 1 11
2020-12-01 us 2 11
2020-12-01 us 3 12
2020-12-01 us 4 13
2020-12-01 us 5 14
2020-12-01 us 6 14
2020-12-01 us 7 14

在 t1 表 - 带有国家和 inst 日期的 id 列表。在事件表 - 按 id 的事件日期

【问题讨论】:

标签: sql group-by clickhouse


【解决方案1】:

使用group by:

select inst_date, country, 
    (event_day - inst_date) as date_difference,
    count(*) as events_count
from t1
all left join (
    select distinct id, toDate(event_date) as event_day, 1 as event
    from events
) as events_ using id
where (event_day - inst_date) between 0 and 7
group by inst_date, country, (event_day - inst_date)
order by inst_date, country, date_difference;

我强烈建议在查询中的所有列之前加上它们所属的表,这样查询就可以明确地了解底层数据结构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多