【发布时间】: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”为真时的帖子数。
我已经查询了按日期对 cmets 排序并按 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