【问题标题】:How to count users group by time interval如何按时间间隔统计用户组
【发布时间】:2022-01-16 07:20:54
【问题描述】:

我有一个带有用户 ID 和 created_at 类型的时间戳的表,我想计算在给定日期的 3 小时间隔内有多少用户创建了他们的帐户。到目前为止,我已经创建了这个查询,但我无法获得每三个小时的计数

with time_cte AS (
    SELECT time_sample from
            generate_series('2021-12-01'::date, '2021-12-01'::date + interval '1 day', interval '3 hour')
                as time_sample
) SELECT time_sample, count(u.id) FROM time_cte
    join users u ON u.created_at::date = '2021-12-01'::date
                                       GROUP BY time_sample;

我可以获得系列和计数,但它们是当天的用户总数

我得到的输出

time_sample                count
2021-12-01 00:00:00.000000, 4
2021-12-01 03:00:00.000000, 4
2021-12-01 06:00:00.000000, 4
2021-12-01 09:00:00.000000, 4
2021-12-01 12:00:00.000000, 4
2021-12-01 15:00:00.000000, 4
2021-12-01 18:00:00.000000, 4
2021-12-01 21:00:00.000000, 4
2021-12-02 00:00:00.000000, 4

我期望的输出是

time_sample                count
2021-12-01 00:00:00.000000, 0
2021-12-01 03:00:00.000000, 0
2021-12-01 06:00:00.000000, 3
2021-12-01 09:00:00.000000, 1
2021-12-01 12:00:00.000000, 0
2021-12-01 15:00:00.000000, 0
2021-12-01 18:00:00.000000, 0
2021-12-01 21:00:00.000000, 0
2021-12-02 00:00:00.000000, 0

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    对于 PostgreSQL 14,您可以使用内置的 date_bin 函数。

    select 
      date_bin(interval '3 hours', created_at, date_trunc('day', created_at)) as time_slot,
      count(*) as cnt
    from users 
    group by time_slot
    order by time_slot;
    

    对于 14 之前的 PostgreSQL 版本,您可以使用 this 实现 date_bin

    【讨论】:

      猜你喜欢
      • 2012-02-18
      • 2020-10-16
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      • 2019-08-07
      • 2015-06-15
      • 2021-07-23
      相关资源
      最近更新 更多