计算组中的额外列

时间:2015-03-15 13:00:50

标签: sql-server sql-server-2005 group-by

确定这应该很简单,但我有brain fart

在SQL Server 2005中,如何为GROUP BY查询添加“额外计数”?

考虑以下内容......

;WITH DATA AS (
    SELECT 1 AS ID, 1 AS TYPEID, 0 AS ACTIONNEEDED 
    UNION
    SELECT 2 AS ID, 1 AS TYPEID, 0 AS ACTIONNEEDED 
    UNION
    SELECT 3 AS ID, 2 AS TYPEID, 0 AS ACTIONNEEDED 
    UNION
    SELECT 4 AS ID, 2 AS TYPEID, 1 AS ACTIONNEEDED 
    UNION
    SELECT 5 AS ID, 2 AS TYPEID, 0 AS ACTIONNEEDED 
)
SELECT TYPEID, COUNT(*) AS TOTAL
FROM DATA
GROUP BY TYPEID

结果是......

TYPEID  TOTAL
1       2
2       3

但我需要的是一个额外的列,总计ACTIONNEEDED=1 ...

的行数
TYPEID  TOTAL ACTIONNEEDED
1       2     0
2       3     1

注意:遗憾的是由于项目限制,我仅限于SQL Server 2005兼容的答案

1 个答案:

答案 0 :(得分:2)

您可以将SUM与内部CASE声明一起使用:

SELECT 
    TYPEID, 
    COUNT(*) AS TOTAL, 
    SUM(CASE WHEN ActionNeeded = 1 THEN 1 ELSE 0 END) AS ACTIONNEEDED
FROM DATA
GROUP BY TYPEID