除了Get total sum of video comments for each video之外,我还注意到无法使用v.commentCount,因为我清除了一些数据,但现在该列不准确。
所以我需要在评论表中计算videoId评论和所有videoID评论。
我有台视频
videoId | channelId
a | 1
b | 1
c | 2
d | 2
和一个表注释。 video.channelId映射到comment.videoID_channelID
commentID | replyID | videoID | videoID_channelID | textOriginal
c1 | NULL | a | 1 | "test"
c2 | NULL | a | 1 | "some text"
NULL | r1.c1 | b | 1 | "asdad"
NULL | r2.c1 | b | 1 | "xxx"
c5 | NULL | b | 1 | "yyy"
c6 | NULL | c | 2 | "zzz"
c7 | NULL | d | 2 | "-...-."
对于每个videoId,我都需要commentCount(每个videoId有多少条评论)以及该频道的所有commentCounts的总和(对于channelID的每个视频有多少总评论?)。
所以最终结果应该是:
videoId | channelId | commentCount | commentCount_sum
a | 1 | 2 | 5
b | 1 | 3 | 5
c | 2 | 1 | 2
d | 2 | 1 | 2
到目前为止,我的代码:
SELECT v.videoId,
v.channelId,,,
count(c.textOriginal) commentCount,
count(c.textOriginal) over (partition by c.videoID_channelID) as commentCount_sum,
FROM videos v
JOIN comments c
ON v.videoId = c.videoID
GROUP BY v.videoId
ORDER BY commentCount_sum ASC
但是我没有得到正确的commentCount_sum?
答案 0 :(得分:1)
您可以在子查询中进行汇总,然后在外部查询中进行窗口计数:
select t.*, sum(commentCount) over(partition by channelId) commentCount_sum
from (
select v.videoId, v.channelId, count(*) commentCount
from video v
inner join comments c on c.videoID = v.videoId and c.videoID_channelID = v.channelId
group by v.videoId, v.channelId
) t
我还修复了您的加入条件(您在channelId
上缺少加入条件)。
videoId | channelId | commentCount | commentCount_sum :------ | :-------- | :----------- | :--------------- a | 1 | 2 | 5 b | 1 | 3 | 5 c | 2 | 1 | 2 d | 2 | 1 | 2
答案 1 :(得分:0)
这可以做到:
SELECT v.videoId,
v.channelId,
count(c.textOriginal) commentCount,
(select count(c.textOriginal) from comments d where d.videoID_channelID = v.channelId group by d.videoID_channelID) as commentCount_sum,
FROM videos v
JOIN comments c
ON v.videoId = c.videoID
GROUP BY v.videoId
ORDER BY commentCount_sum ASC
答案 2 :(得分:0)
如果您想不使用window function
来执行此操作...我将它们隔开了,您可以看到我们正在做什么。正如GMB所指出的,您缺少在channelID上的加入。
select a.*, b.channel_comment_count
from
(select v.videoid, v.channelid, count(c.textoriginal) as video_comment_count
from cte1 v join cte2 c on v.videoid = c.videoid and v.channelid = c.videoid_channelid
group by v.channelid, v.videoid) a
inner join
(select channelid, count(c.textoriginal) as channel_comment_count
from cte1 v join cte2 c on v.videoid = c.videoid and v.channelid = c.videoid_channelid
group by v.channelid) b
on a.channelid=b.channelid
OR
with cte as
(select v.*, c.textOriginal from cte1 v join cte2 c on v.videoid = c.videoid and v.channelid = c.videoid_channelid)
select a.*, b.channel_comment_count
from
(select videoid, channelid, count(textoriginal) as video_comment_count
from cte group by channelid, videoid) a
inner join
(select channelid, count(textoriginal) as channel_comment_count
from cte group by channelid) b
on a.channelid=b.channelid