【问题标题】:Query based on number of records on distinct days between two dates根据两个日期之间不同日期的记录数进行查询
【发布时间】:2021-09-16 08:48:56
【问题描述】:

给定以下架构:

用户

column type
id uuid
username varchar(255)

参赛作品

column type
id uuid
user_id uuid
inserted_at timestamp

如何查询在两个日期之间每天创建n 条目的用户列表。例如,所有在 9 月 1 日至 9 月 15 日之间的 10 天内有条目的用户。

请注意,用户可能在一天内有多个条目。我对两个日期之间不同日期的条目感兴趣。

我正在使用 Postgres,但我想这是一个更广泛的 sql 问题。

【问题讨论】:

  • 样本数据很好,但您也应该指定预期结果。

标签: sql postgresql


【解决方案1】:
select u.id as user_id, max(u.username), count(e.id) as entries_count
from users u
    inner join (
      select max(id) as id, user_id, max(inserted_at) as inserted_at
      from entries
      group by user_id cast(inserted_at as date) 
    ) e on u.id = e.user_id
where e. inserted_at between {start_date} and {end_date}
group by u.id having count(e.id)>X

{start_date} => 时间范围的开始

{end_date} => 时间范围结束

X => 至少应该有多少条目

这里的时间范围包括在内

【讨论】:

    猜你喜欢
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    相关资源
    最近更新 更多