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;
相关推荐
leo__52012 分钟前
在Ubuntu中设置开机自动运行(sudo)指令的指南
服务器·ubuntu·postgresql
liujing1023292924 分钟前
Day09_刷题niuke20250609
java·c++·算法
不7夜宵27 分钟前
力扣热题100 k个一组反转链表题解
算法·leetcode·链表
159423156333 分钟前
QT使用WxSQLite3打开加密数据库并查询
数据库·qt·sqlite
程序员阿超的博客1 小时前
【数据篇】持久化核心:整合 JPA/MyBatis 实现优雅的数据库操作
数据库·mybatis
蒟蒻小袁1 小时前
力扣面试150题--课程表
算法·leetcode·面试
闻缺陷则喜何志丹2 小时前
【动态规划】B4336 [中山市赛 2023] 永别|普及+
c++·算法·动态规划·洛谷
不二狗3 小时前
每日算法 -【Swift 算法】电话号码字母组合
开发语言·算法·swift
AL流云。3 小时前
【优选算法】分治
数据结构·算法·leetcode·排序算法