sql - 查找在 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
任何人都可以帮助我确认我的解决方案或提出另一个解决方案吗?
解决方案
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';
推荐阅读
- javascript - MaterializeCSS 中的 getInstance 方法是什么
- ionic-framework - 如何使用 Ionic Capacitor Filesystem 插件读取资产文件夹中的文件/文件夹
- python - 在一张 Excel 表格中转换多个 TDMS 元数据文件
- node.js - 为什么我的 ExpressJS 无法获取静态目录?
- flatpickr - flatpickr 星期一的第一天和速记currentMonth
- c++ - Writefile() 根据数据长度写入数据失败
- javascript - Puppeteer:检测和访问循环打开的弹出窗口的正确方法
- python - Python 2.7 如何在“imp”导入的代码导入语句上欺骗 python
- asp.net - 为什么gridview不保留分页之间的复选框值?
- python - python pandas - 更新数据框,替换值,添加新行