TSQL - HAVING子句中的聚合

时间:2016-09-27 13:55:54

标签: sql-server tsql aggregate where-clause

我知道这个问题已经被问了很多但是当我解决错误信息并使用HAVING子句时,我仍然收到了可怕的问题:

An aggregate may not appear in the WHERE clause unless it is in a 
subquery contained in a HAVING clause or a select list, 
and the column being aggregated is an outer reference.

我做错了什么,在这里?

SELECT
mr.ClubKeyNumber,
COUNT(mr.MonthlyReportID),
SUM(CONVERT(int,mr.Submitted))
FROM MonthlyReport mr
WHERE mr.ReportYear = 2014
AND COUNT(mr.MonthlyReportID) = 12
GROUP BY mr.ClubKeyNumber
HAVING (SUM(CONVERT(int,mr.Submitted))) > 11

1 个答案:

答案 0 :(得分:6)

问题不在于HAVING条款中的WHERE条款。

您的count子句中有一个汇总where,请尝试以下操作:

SELECT
mr.ClubKeyNumber,
COUNT(mr.MonthlyReportID),
SUM(CONVERT(int,mr.Submitted))
FROM MonthlyReport mr
WHERE mr.ReportYear = 2014
GROUP BY mr.ClubKeyNumber
HAVING (SUM(CONVERT(int,mr.Submitted))) > 11 and COUNT(mr.MonthlyReportID) = 12

where子句检查group by子句之前聚合的每一行。 <{1}}之前 count MonthlyReportID之后<{1}},<{1}}之后 {}}

Here is a simple example你可以用来证明vs的位置。