首页 > 解决方案 > 查找在 X 范围日期发表第一条评论的帖子数

问题描述

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

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

帖子:

ID 标题 is_public
1 帖子 1 真的
2 帖子 2 真的
3 帖子 3 错误的

评论:

ID post_id 文本 created_at
1 1 评论 1 2021-01-01
2 1 评论 2 2021-01-02
3 2 评论 3 2021-01-03
4 2 评论 4 2021-01-04
5 3 评论 5 2021-01-04

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

我已经进行了查询,按日期排序评论并按 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

任何人都可以帮助我确认我的解决方案或提出另一个解决方案吗?

标签: sqlpostgresqlactiverecord

解决方案


I want to calculate is the count of posts where its first comment was created between 2 dates and when the variable 'is_public' of the posts is true

This is basically filtering:

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';

推荐阅读