问题描述
假设我有一个表,其中 user_id
类型为 Int32
,login_time
为 DateTime
,格式为 UTC
。 user_id
不是唯一的,所以 SELECT user_id,login_time FROM some_table;
给出以下结果:
┌─user_id─┬──login_time─┐
│ 1 │ 2021-03-01 │
│ 1 │ 2021-03-01 │
│ 1 │ 2021-03-02 │
│ 2 │ 2021-03-02 │
│ 2 │ 2021-03-03 │
└─────────┴─────────────┘
如果我运行 SELECT COUNT(*) as count,toDate(login_time) as l FROM some_table GROUP BY l
,我会得到以下结果:
┌─count───┬──login_time─┐
│ 2 │ 2021-03-01 │
│ 2 │ 2021-03-02 │
│ 1 │ 2021-03-03 │
└─────────┴─────────────┘
我想重新格式化结果以每周显示 COUNT
,而不是像我目前所做的那样每天显示。
我对上述示例的结果可能如下所示:
┌──count──┬──year─┬──month──┬─week ordinal┐
│ 5 │ 2021 │ 03 │ 1 │
│ 0 │ 2021 │ 03 │ 2 │
│ 0 │ 2021 │ 03 │ 3 │
│ 0 │ 2021 │ 03 │ 4 │
└─────────┴───────┴─────────┴─────────────┘
我浏览了文档,发现了一些有趣的功能,但没有设法让它们解决我的问题。
我以前从未与 clickhouse
合作过,并且对 sql 不是很熟悉,这就是我在这里寻求帮助的原因。
解决方法
试试这个查询:
select count() count,toYear(start_of_month) year,toMonth(start_of_month) month,toWeek(start_of_week) - toWeek(start_of_month) + 1 AS "week ordinal"
from (
select *,toStartOfMonth(login_time) start_of_month,toStartOfWeek(login_time) start_of_week
from (
/* emulate test dataset */
select data.1 user_id,toDate(data.2) login_time
from (
select arrayJoin([
(1,'2021-02-27'),(1,'2021-02-28'),'2021-03-01'),'2021-03-02'),(2,'2021-03-03'),'2021-03-08'),'2021-03-16'),'2021-04-01')]) data)
)
)
group by start_of_month,start_of_week
order by start_of_month,start_of_week
/*
┌─count─┬─year─┬─month─┬─week ordinal─┐
│ 1 │ 2021 │ 2 │ 4 │
│ 1 │ 2021 │ 2 │ 5 │
│ 5 │ 2021 │ 3 │ 1 │
│ 1 │ 2021 │ 3 │ 2 │
│ 1 │ 2021 │ 3 │ 3 │
│ 1 │ 2021 │ 4 │ 1 │
└───────┴──────┴───────┴──────────────┘
*/