计算组中的额外列
Calculate extra column in group by
当然这应该很简单,但我有一个brain fart。
在 SQL Server 2005 中,如何将 "extra count" 添加到 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 兼容的答案
您可以将 SUM
与内部 CASE
语句一起使用:
SELECT
TYPEID,
COUNT(*) AS TOTAL,
SUM(CASE WHEN ActionNeeded = 1 THEN 1 ELSE 0 END) AS ACTIONNEEDED
FROM DATA
GROUP BY TYPEID
当然这应该很简单,但我有一个brain fart。
在 SQL Server 2005 中,如何将 "extra count" 添加到 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 兼容的答案
您可以将 SUM
与内部 CASE
语句一起使用:
SELECT
TYPEID,
COUNT(*) AS TOTAL,
SUM(CASE WHEN ActionNeeded = 1 THEN 1 ELSE 0 END) AS ACTIONNEEDED
FROM DATA
GROUP BY TYPEID