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;
相关推荐
Anastasiozzzz34 分钟前
MySQL JOIN:底层原理、算法演进与多表性能之谜
算法
Albert Edison4 小时前
【Python】学生管理系统
开发语言·数据库·python
追随者永远是胜利者7 小时前
(LeetCode-Hot100)253. 会议室 II
java·算法·leetcode·go
Jason_Honey27 小时前
【平安Agent算法岗面试-二面】
人工智能·算法·面试
程序员酥皮蛋7 小时前
hot 100 第三十五题 35.二叉树的中序遍历
数据结构·算法·leetcode
追随者永远是胜利者7 小时前
(LeetCode-Hot100)207. 课程表
java·算法·leetcode·go
heimeiyingwang8 小时前
企业供应链 AI 优化:需求预测与智能调度
大数据·数据库·人工智能·机器学习
仰泳的熊猫8 小时前
题目1535:蓝桥杯算法提高VIP-最小乘积(提高型)
数据结构·c++·算法·蓝桥杯
那起舞的日子9 小时前
动态规划-Dynamic Programing-DP
算法·动态规划
山岚的运维笔记9 小时前
SQL Server笔记 -- 第73章:排序/对行进行排序
数据库·笔记·后端·sql·microsoft·sqlserver