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;
相关推荐
nunca_te_rindas几秒前
算法刷体小结汇总(C/C++)20260328
c语言·c++·算法
Sunshine for you3 分钟前
高性能压缩库实现
开发语言·c++·算法
Sunshine for you4 分钟前
C++中的表达式模板
开发语言·c++·算法
qwehjk20085 分钟前
C++中的状态模式
开发语言·c++·算法
2401_873544928 分钟前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
Fortune799 分钟前
自定义类型转换机制
开发语言·c++·算法
nunca_te_rindas9 分钟前
递归实现排列型枚举题目例题
算法
2301_8145902510 分钟前
实时音频处理C++实现
开发语言·c++·算法
会编程的土豆11 分钟前
全面解析数据库锁机制:从行锁到死锁的深度剖析
数据库
tongxh42312 分钟前
5、使用 pgAdmin4 图形化创建和管理 PostgreSQL 数据库
数据库·postgresql