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;
相关推荐
消失的旧时光-194336 分钟前
SQL 第五篇:SQL 如何真正接入 Spring Boot 项目(企业 Mapper 分层实战)
数据库·spring boot·sql
平凡但不平庸的码农7 小时前
Go Slice 详解
算法·golang
dfdfadffa7 小时前
如何用模块化方案组织一个可扩展的前端组件库项目
jvm·数据库·python
2301_812539677 小时前
SQL中如何高效实现分组数据的批量更新_利用窗口函数与JOIN
jvm·数据库·python
2501_901200537 小时前
如何实现SQL存储过程存储过程参数标准化_统一命名规范
jvm·数据库·python
运气好好的8 小时前
Golang怎么用embed嵌入SQL文件_Golang如何将SQL迁移文件嵌入Go程序统一管理【技巧】
jvm·数据库·python
念何架构之路8 小时前
MySql常见ORM
数据库·mysql
xcLeigh9 小时前
KES数据库安全、权限、审计实战
数据库·安全·备份·权限·审计·ssl加密·密码策略
zjy277779 小时前
c++如何实现日志文件的异步落盘功能_基于无锁队列方案【附代码】
jvm·数据库·python
河阿里9 小时前
SQL:深分页问题深度解析
数据库·sql