【问题标题】:Find count of posts where the first comment were made at X range dates查找在 X 范围日期发表第一条评论的帖子数
【发布时间】:2021-07-03 14:54:37
【问题描述】:

我在尝试进行此查询时遇到问题,

我有 2 张桌子,我们称它们为帖子和 cmets:

帖子:

id title is_public
1 post 1 true
2 post 2 true
3 post 3 false

评论:

id post_id text created_at
1 1 comment 1 2021-01-01
2 1 comment 2 2021-01-02
3 2 comment 3 2021-01-03
4 2 comment 4 2021-01-04
5 3 comment 5 2021-01-04

我要计算的是在 2 个日期之间创建第一条评论以及帖子的变量“is_public”为真时的帖子数。

我已经查询了按日期对 cme​​ts 排序并按 post_id 分组,但我不确定它是否正确:

SELECT COUNT(*) 
FROM (SELECT distinct on (c.post_id) c.post_id, c.created_at
FROM comments c
INNER JOIN posts p
ON p.id = c.post_id
WHERE c.created_at >= '2021-01-01' AND c.created_at <= '2021-01-04' AND p.is_public = true
ORDER BY c.post_id, c.created_at ASC) as q1;

日期为“2021-01-01”和“2021-01-04”的预期结果:

2

日期为“2021-01-02”和“2021-01-04”的预期结果:

1

谁能帮我确认我的解决方案或提出另一个解决方案?

【问题讨论】:

    标签: sql postgresql activerecord


    【解决方案1】:

    我要计算的是在 2 个日期之间创建第一条评论以及帖子的变量“is_public”为真时的帖子数

    这基本上是过滤:

    select count(*)
    from posts p
    where p.is_public and
          (select min(c.created_at)
           from comments c
           where c.post_id = p.id
          ) between '2021-01-01' and '2021-01-04';
    

    【讨论】:

    • 谢谢!我想这就是我想要的!
    猜你喜欢
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2016-01-02
    • 1970-01-01
    相关资源
    最近更新 更多