获取每个视频的视频评论总数

时间:2019-12-20 13:49:53

标签: sql sqlite join sum

我有台视频

videoId | channelId | commentCount
a       | 1         | 5
b       | 1         | 3
c       | 2         | 1

和一个表格频道。 video.channelId映射到channel.Id

Id
1
2
3

对于每个videoId,我需要该通道的commentCount和所有commentCounts的总和。

所以最终结果应该是:

videoId | channelId | commentCount | commentCount_sum
a       | 1         | 5            | 8
b       | 1         | 3            | 8
c       | 2         | 1            | 1

到目前为止,我的代码:

SELECT v.videoId, v.channelId, v.commentCount, SUM(v.commentCount) commentCount_sum
FROM videos v
JOIN channels c
ON c.Id = v.channelId
GROUP BY v.videoId

但是我没有为每个videoId获得正确的commentCount_sum-commentCount_sum与commentCount相同吗?

1 个答案:

答案 0 :(得分:1)

SQLite支持窗口功能已有一年多了,这似乎是您想要的:

select v.*,
       sum(v.commentCount) over (partition by v.channel_id) as commentCount_sum
from videos v;

对于您的问题,无需joinchannels。但是,如果需要,可以将其添加到查询中。