TSQL获得2个独立计数的SUM

时间:2014-08-28 23:21:16

标签: sql sql-server tsql stored-procedures

我的查询如下所示:

IF (@action = 'topDepartments')
                BEGIN
                    SELECT   TOP 50 E.[DepartmentDesc] AS department,
                                    COUNT(N.[nomineeQID]) AS totalNominations,
                                    COUNT(S.[subQID]) AS totalSubmissions
                    FROM     empTable AS E
                             LEFT OUTER JOIN
                             empowermentSubmissions AS S
                             ON E.[qid] = S.[subQID]
                             LEFT OUTER JOIN
                             empowermentSubmissions AS N
                             ON E.[qid] = N.[nomineeQID]
                    WHERE    N.[statusID] = 3
                             AND N.[locationID] = @locale
                    GROUP BY E.[DepartmentDesc]
                    ORDER BY totalSubmissions DESC
                    FOR      XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root');
                END

一切都很好用但是我想将两个计数一起作为总计,然后按总数排序。

我试了一下,但我一直收到错误

  

无法对包含聚合或子查询的表达式执行聚合函数。

是否有特定的方法需要这样做?

1 个答案:

答案 0 :(得分:2)

当在分组的查询中,并且您想要使用聚合值时,将整个聚合函数视为列,即COUNT(N.[nomineeQID])是一列。因此,在您的情况下,只需将2个聚合一起添加进行计算。

IF (@action = 'topDepartments')
                BEGIN
                    SELECT   TOP 50 E.[DepartmentDesc] AS department,
                                    COUNT(N.[nomineeQID]) AS totalNominations,
                                    COUNT(S.[subQID]) AS totalSubmissions, 
                                    COUNT(N.[nomineeQID])
                                    + COUNT(S.[subQID]) AS ALLSubmissions
                    FROM     empTable AS E
                             LEFT OUTER JOIN
                             empowermentSubmissions AS S
                             ON E.[qid] = S.[subQID]
                             LEFT OUTER JOIN
                             empowermentSubmissions AS N
                             ON E.[qid] = N.[nomineeQID]
                    WHERE    N.[statusID] = 3
                             AND N.[locationID] = @locale
                    GROUP BY E.[DepartmentDesc]
                    ORDER BY totalSubmissions DESC
                    FOR      XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root');
                END

顺便说一句,当我们以这种方式编写查询时,它可能看起来很“昂贵”,但是优化器通常会认识到它可以重复使用计算,所以它实际上没有它看起来那么糟糕。