我有sql;
select
Program,
CASE WHEN ClassMissed = 0 THEN COUNT(ClassMissed) ELSE 0 END as Completed,
CASE WHEN ClassMissed = 1 THEN COUNT(ClassMissed) ELSE 0 END as One_Days_Missed,
CASE WHEN ClassMissed = 2 THEN COUNT(ClassMissed) ELSE 0 END as Two_Days_Missed,
CASE WHEN ClassMissed = 3 THEN COUNT(ClassMissed) ELSE 0 ENd as Three_Days_Missed
from
#temp
group by Program,ClassMissed
这让我在下面说出来:
Program | Completed | One_Days_Missed | Two_Days_Missed |Three_Days_Missed
________________________________________________________________________________
Prog1 | 0 | 19 | 0 | 0
Prog1 | 0 | 0 | 0 | 2

但我期待下表
Program | Completed | One_Days_Missed | Two_Days_Missed |Three_Days_Missed
________________________________________________________________________________
Prog1 | 0 | 19 | 0 | 2

我必须通过 Classmissed 进行分组才能运行查询。
请给我更好的解决方案吗?
谢谢
答案 0 :(得分:1)
您应该使用SUM(CASE WHEN..END)
。
CREATE TABLE #Temp(
Program VARCHAR(20),
ClassMissed INT
)
INSERT INTO #Temp VALUES
('Prog1', 1), ('Prog1', 1), ('Prog1', 1),
('Prog1', 1), ('Prog1', 1), ('Prog1', 1),
('Prog1', 1), ('Prog1', 1), ('Prog1', 1),
('Prog1', 1), ('Prog1', 1), ('Prog1', 1),
('Prog1', 1), ('Prog1', 1), ('Prog1', 1),
('Prog1', 1), ('Prog1', 1), ('Prog1', 3),
('Prog1', 1), ('Prog1', 1), ('Prog1', 3);
SELECT
Program,
SUM(CASE WHEN ClassMissed = 0 THEN 1 ELSE 0 END) AS Completed,
SUM(CASE WHEN ClassMissed = 1 THEN 1 ELSE 0 END) AS One_Days_Missed,
SUM(CASE WHEN ClassMissed = 2 THEN 1 ELSE 0 END) AS Two_Days_Missed,
SUM(CASE WHEN ClassMissed = 3 THEN 1 ELSE 0 END) AS Three_Days_Missed
FROM #Temp
GROUP BY Program
DROP TABLE #Temp
<强> RESULT 强>
Program Completed One_Days_Missed Two_Days_Missed Three_Days_Missed
-------------------- ----------- --------------- --------------- -----------------
Prog1 0 19 0 2