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;
相关推荐
Maggie_ssss_supp5 小时前
Linux-MySQL数据类型&表操作
数据库·mysql
Emilin Amy5 小时前
【C++】【STL算法】那些STL算法替代的循环
开发语言·c++·算法·ros1/2
廋到被风吹走5 小时前
【数据库】【MySQL】高可用架构深度解析:从主从复制到自动切换
数据库·mysql·架构
IT邦德6 小时前
PostgreSQL 通过 mysql_fdw连通MySQL实战
数据库·mysql·postgresql
難釋懷6 小时前
Redis 通用命令
数据库·redis·缓存
Hcoco_me6 小时前
大模型面试题74:在使用GRPO训练LLM时,训练数据有什么要求?
人工智能·深度学习·算法·机器学习·chatgpt·机器人
天赐学c语言6 小时前
1.16 - 二叉树的中序遍历 && 动态多态的实现原理
数据结构·c++·算法·leecode
hanqunfeng6 小时前
(九)Redis 命令及数据类型 -- Set
数据库·redis·bootstrap
企业对冲系统官6 小时前
期货与期权一体化平台风险收益评估方法与模型实现
运维·服务器·开发语言·数据库·python·自动化
IT邦德6 小时前
PostgreSQL通过Oracle_FDW连通Oracle实战
数据库·postgresql·oracle