使用COUNT功能加入三个表并按一个字段分组

时间:2014-05-05 16:22:14

标签: sql join group-by

我有三张桌子 - 章节,主题和评论。

简单视图:

-SectionId

主题

-ThemeId -SectionId

评论

-CommentId -ThemeId

我需要编写sql查询来获得如下结果:

-SectionId -CountOfThemes -CountOfComments

解决:

Select 
    Section.SectionId As SessionId, 
    Section.SectionTitle As SessionTitle,
    Count(Distinct Theme.ThemeId) As CountTheme,
    Count(Distinct Comment.CommentId) As CountComment

From Section
Left Join Theme On Section.SectionId = Theme.SectionId
LEFT JOIN Comment ON Theme.ThemeId = Comment.ThemeId
Group By 
    Section.SectionId,
    Section.SectionTitle

1 个答案:

答案 0 :(得分:1)

尝试使用COUNT(DISTINCT Theme.ThemeId)和COUNT(DISTINCT Comment.CommentId)

我认为您的问题是主题和评论之间存在一对多的关系,因此您会在有多个评论的地方获得重复的ThemeIds。

您的代码:left Join Comment On Comment.ThemeId = Theme.ThemeId

我会考虑更改为LEFT JOIN Comment ON Theme.ThemeId = Comment.ThemeId