leetcode 1241每个帖子的评论数(postgresql)

需求

编写 SQL 语句以查找每个帖子的评论数。

结果表应包含帖子的 post_id 和对应的评论数 number_of_comments 并且按 post_id 升序排列。

Submissions 可能包含重复的评论。您应该计算每个帖子的唯一评论数。

Submissions 可能包含重复的帖子。您应该将它们视为一个帖子。

结果表应该按 post_id 升序排序。

输入

输出

sql 复制代码
with t1 as (
    -- 查询出帖子数,并去重
    select distinct sub_id
    from submissions
    where parent_id is null
),t2 as (
    -- 查询出评论数,并去重
    select distinct sub_id,parent_id
    from submissions
    where parent_id notnull
)
select t1.sub_id as post_id,count(parent_id) as number_of_comments
from t1 left join t2
on t1.sub_id=t2.parent_id
group by t1.sub_id
order by post_id;
相关推荐
今晚务必早点睡15 小时前
微服务改数据库密码后服务仍能访问?一次“看似异常、实则常见”的生产现象全解析
数据库·微服务·oracle
君义_noip15 小时前
信息学奥赛一本通 1661:有趣的数列 | 洛谷 P3200 [HNOI2009] 有趣的数列
c++·算法·组合数学·信息学奥赛·csp-s
程序员:钧念15 小时前
深度学习与强化学习的区别
人工智能·python·深度学习·算法·transformer·rag
英英_16 小时前
MATLAB数值计算基础教程
数据结构·算法·matlab
一起养小猫17 小时前
LeetCode100天Day14-轮转数组与买卖股票最佳时机
算法·leetcode·职场和发展
老师我太想进步了202617 小时前
cmd连接MySQL及相关查询
数据库·mysql
hele_two17 小时前
快速幂算法
c++·python·算法
l1t17 小时前
利用DeepSeek将python DLX求解数独程序格式化并改成3.x版本
开发语言·python·算法·数独
jllllyuz18 小时前
基于子集模拟的系统与静态可靠性分析及Matlab优化算法实现
算法·matlab·概率论
程序员-King.18 小时前
day143—递归—对称二叉树(LeetCode-101)
数据结构·算法·leetcode·二叉树·递归