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;
相关推荐
生物信息与育种11 小时前
全基因组重测序及群体遗传与进化分析技术服务指南
人工智能·深度学习·算法·数据分析·r语言
AI人工智能+电脑小能手11 小时前
【大白话说Java面试题】【Java基础篇】第23题:ConcurrentHashMap的底层原理是什么
java·开发语言·算法·哈希算法·散列表·hash
葳_人生_蕤11 小时前
hot100——回溯和DFS、BFS
算法·深度优先
Eloudy11 小时前
Steane码的稳定子的生成元集计算过程
算法
MegaDataFlowers11 小时前
快速算法验证流水线
算法
hsD5mSMu511 小时前
从零开始学Flink:Flink SQL 极简入门
大数据·sql·flink
Aaron158812 小时前
27DR/47DR/67DR技术对比及应用分析
人工智能·算法·fpga开发·硬件架构·硬件工程·信息与通信·基带工程
alphaTao12 小时前
LeetCode 每日一题 2026/4/27-2026/5/3
算法·leetcode
北重楼0112 小时前
如何取消一个挂起的 PostgreSQL 查询
数据库·postgresql
与数据交流的路上12 小时前
mysql参数-优化器 range_optimizer_max_mem_size 相关
数据库·mysql