Sql 使用计数函数连接三个表并按一个字段分组

Sql 使用计数函数连接三个表并按一个字段分组,sql,join,group-by,Sql,Join,Group By,我有三个表格——章节、主题和评论 简单视图: 小节 -截面ID 主题 -特梅德 -截面ID 评论 -评论 -特梅德 我需要编写sql查询以获得如下结果: -截面ID -伯爵夫人 -建议数 断然的: 尝试使用COUNT(DISTINCT Theme.ThemeId)和COUNT(DISTINCT Comment.CommentId) 我认为你的问题是,你的主题和评论之间有一对多的关系,因此当有多条评论时,你会得到重复的主题 还有您的代码:left Join Comment On Comment.T

我有三个表格——章节、主题和评论

简单视图:

小节 -截面ID

主题 -特梅德 -截面ID

评论 -评论 -特梅德

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

-截面ID -伯爵夫人 -建议数

断然的: 尝试使用COUNT(DISTINCT Theme.ThemeId)和COUNT(DISTINCT Comment.CommentId)

我认为你的问题是,你的主题和评论之间有一对多的关系,因此当有多条评论时,你会得到重复的主题

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


我会考虑更改为<代码>左联接评论.MeMID=注释。它起作用了

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