给定
表A
Id INTEGER Name VARCHAR(50)
表B
Id INTEGER FkId INTEGER ; Foreign key to Table A
我希望计算每个FkId值的出现次数:
FkId
SELECT FkId, COUNT(FkId) FROM B GROUP BY FkId
现在,我只想输出的名称Table A。
Table A
这将不起作用:
SELECT FkId, COUNT(FkId), a.Name FROM B b INNER JOIN A a ON a.Id=b.FkId GROUP BY FkId
因为a.Name不包含在GROUP BY子句中(产生is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause错误)。
a.Name
GROUP BY
is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
关键是要像这样从输出中移出
FkId Count 1 42 2 25
这样输出
FkId Count Name 1 42 Ronald 2 22 John
该错误消息在SO上有很多匹配项,但是某些匹配项
如何在查询输出中 有效地 包含联接的字段Table B(与的关系为1:1 FkId)?
Table B
您可以尝试如下操作:
;WITH GroupedData AS ( SELECT FkId, COUNT(FkId) As FkCount FROM B GROUP BY FkId ) SELECT gd.*, a.Name FROM GroupedData gd INNER JOIN dbo.A ON gd.FkId = A.FkId
创建一个CTE(公用表表达式)来处理上的分组/计数Table B,然后将该结果(每行一行FkId)加入到最终结果集中,Table A并从中获取更多的列Table A。