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;
相关推荐
leoufung5 分钟前
LeetCode 149: Max Points on a Line - 解题思路详解
算法·leetcode·职场和发展
样例过了就是过了6 分钟前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
2401_8323655211 分钟前
JavaScript中rest参数(...args)取代arguments的优势
jvm·数据库·python
HXDGCL14 分钟前
矩形环形导轨:自动化循环线的核心运动单元解析
运维·算法·自动化
谭欣辰25 分钟前
C++ 排列组合完整指南
开发语言·c++·算法
2301_7796224128 分钟前
Go语言怎么用信号量控制并发_Go语言semaphore信号量教程【入门】
jvm·数据库·python
代码中介商39 分钟前
银行管理系统的业务血肉 —— 流程、状态机、输入校验与持久化(下篇)
c语言·算法
2301_7662834440 分钟前
c++如何将控制台输出保存到文件_cout重定向到txt【详解】
jvm·数据库·python
北极的冰箱43 分钟前
MySQL Ver 8.0.41 for macos14.7密码遗忘
数据库·mysql
foundbug9991 小时前
自适应滤除直达波干扰的MATLAB实现
开发语言·算法·matlab