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;
相关推荐
周杰伦_Jay6 分钟前
【终端使用MySQL】MySQL 数据库核心操作全解析:从入门到性能优化
数据库·mysql·性能优化
刘一哥GIS9 分钟前
Windows环境搭建:PostGreSQL+PostGIS安装教程
数据库·python·arcgis·postgresql·postgis
Mr.Ja28 分钟前
【LeetCode热题100】No.11——盛最多水的容器
算法·leetcode·贪心算法·盛水最多的容器
云和数据.ChenGuang29 分钟前
uri: mongodb://jack:123456@localhost://27017 数据库访问其他的写法
数据库·mongodb·oracle
冷徹 .40 分钟前
2024ICPC区域赛香港站
数据结构·c++·算法
ManageEngineITSM1 小时前
IT 服务自动化的时代:让效率与体验共进
运维·数据库·人工智能·自动化·itsm·工单系统
SelectDB1 小时前
Apache Doris 内部数据裁剪与过滤机制的实现原理
数据库·数据分析·github
Derrick__11 小时前
Python访问数据库——使用SQLite
数据库·python·sqlite
Databend1 小时前
Databend 九月月报:自增列 AUTOINCREMENT 与行级安全
数据库
浅川.251 小时前
xtuoj string
开发语言·c++·算法