需求
编写 SQL 语句以查找每个帖子的评论数。
结果表应包含帖子的 post_id 和对应的评论数 number_of_comments 并且按 post_id 升序排列。
Submissions 可能包含重复的评论。您应该计算每个帖子的唯一评论数。
Submissions 可能包含重复的帖子。您应该将它们视为一个帖子。
结果表应该按 post_id 升序排序。
输入
输出
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;