我正在努力寻找以下问题的解决方案。 假设,有一个像这样的表
COL1 FLAG
aaa 1
aaa 0
aaa 1
bbb 0
我需要编写一个查询来获得以下输出:
COL1_VALUE FLAGGED TOTAL
aaa 2 3
bbb 0 1
其中FLAGGED列包含FLAG = 1的'aaa'行值的总计数,TOTAL列是包含'aaa'的行的总数,换句话说,查找包含'aaa'的行数被标记与包含'aaa'的总行数有关。是否可以使用单个查询? (即不使用临时表等)。
(MSSQL2008)
答案 0 :(得分:5)
SELECT COL1 AS COL1_VALUE,
COUNT(CASE WHEN FLAG = 1 THEN 1 END) AS FLAGGED,
COUNT(*) AS TOTAL
FROM YourTable
GROUP BY COL1
答案 1 :(得分:4)
SELECT COL1, SUM(FLAG) AS FLAGGED, Count(*) AS TOTAL from tbl GROUP BY COL1
答案 2 :(得分:0)
SELECT Tab.COL1 AS COL1_VALUE,
SUM(CASE WHEN Tab.FLAG = 1 THEN 1 ELSE 0 END) AS FLAGGED,
COUNT(*) AS TOTAL
FROM Tab
GROUP BY Tab.COL1