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;
相关推荐
CSharp精选营6 分钟前
SQL Server安装避坑:这8个奇葩报错你遇到过几个?
数据库·sql server·安装指南·避坑
一叶落4389 分钟前
题目:15. 三数之和
c语言·数据结构·算法·leetcode
一勺菠萝丶12 分钟前
Flowable + Spring 集成踩坑:流程结束监听器查询历史任务为空 & 获取不到审批意见
java·数据库·spring
RDCJM30 分钟前
mysql表添加索引
数据库·mysql
老鱼说AI1 小时前
CUDA架构与高性能程序设计:异构数据并行计算
开发语言·c++·人工智能·算法·架构·cuda
czlczl200209252 小时前
Redis命令处理逻辑模型
数据库·redis·缓存
罗湖老棍子2 小时前
【例 1】数列操作(信息学奥赛一本通- P1535)
数据结构·算法·树状数组·单点修改 区间查询
spring2997922 小时前
LangChain-08 Query SQL DB 通过GPT自动查询SQL
数据库·sql·langchain
San30.2 小时前
深入浅出 RAG 与向量数据库:从 Milvus 基础到电子书级语义搜索实战
数据库·人工智能·langchain·llm·milvus·rag
big_rabbit05022 小时前
[算法][力扣222]完全二叉树的节点个数
数据结构·算法·leetcode