【问题标题】:Display COUNT(*) for every week instead of every day每周而不是每天显示 COUNT(*)
【发布时间】:2021-04-18 17:45:16
【问题描述】:

假设我有一个user_id 类型为Int32login_timeDateTime 格式为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 的经验也不是很丰富,这就是我在这里寻求帮助的原因。

【问题讨论】:

  • “周序数”是相对于每个月的开始还是相对于年初?
  • @datosula:相对于每个月的开始

标签: sql clickhouse


【解决方案1】:

试试这个查询:

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'),      
          (1, '2021-03-01'),
          (1, '2021-03-01'),
          (1, '2021-03-02'),
          (2, '2021-03-02'),
          (2, '2021-03-03'),
          (2, '2021-03-08'),
          (2, '2021-03-16'),
          (2, '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 │
└───────┴──────┴───────┴──────────────┘
*/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 2013-10-31
    • 2014-08-06
    • 2013-03-10
    • 1970-01-01
    相关资源
    最近更新 更多