如何在SQL中组合多个count语句

时间:2014-06-06 10:33:47

标签: sql sql-server select count sum

我有一个包含ID列表的表,每个ID的状态为HW,HB,PIP或TBC。

我想计算每种状态的人数,所以我会看一张表格

HW HB PIP TBC

45 27 9 49

我的那一刻

    (SELECT COUNT(*) AS 'StatusHW' From HomeworkerStatus WHERE Status='Homeworker')
    UNION       
    (SELECT COUNT(*) AS 'StatusHB' From HomeworkerStatus WHERE Status='Home Based')
    UNION
    (SELECT COUNT(*) AS 'StatusPIP' From HomeworkerStatus WHERE Status='PIP') 
    UNION
    (SELECT COUNT(*) AS 'StatusTBC' From HomeworkerStatus WHERE Status='TBC')           

返回

StatusHW

1 45

2 27

3 9

4 49

我也试过

    SELECT Status,
    sum(case when Status = 'Homeworker' then 1 else 0 end) StatusHW,
    sum(case when Status = 'Home Based' then 1 else 0 end) StatusHB,
    sum(case when Status = 'PIP' then 1 else 0 end) StatusPIP,
    sum(case when Status = 'TBC' then 1 else 0 end) StatusTBC
    FROM HomeworkerStatus
    GROUP BY Status

这会返回一个4x4表,其中包含行1,2,3,4和列Status,StatusHW,...,StatusTBC。这更接近我所追求的,但仍然不对。

任何帮助都将不胜感激。

由于

2 个答案:

答案 0 :(得分:5)

在汇总为:

时,只需删除已处理这些条件的group by
 SELECT 
    -- Status,
    sum(case when Status = 'Homeworker' then 1 else 0 end) StatusHW,
    sum(case when Status = 'Home Based' then 1 else 0 end) StatusHB,
    sum(case when Status = 'PIP' then 1 else 0 end) StatusPIP,
    sum(case when Status = 'TBC' then 1 else 0 end) StatusTBC
    FROM HomeworkerStatus
    -- GROUP BY Status

答案 1 :(得分:4)

如果您只想要一行,请不要GROUP BY Status

SELECT
sum(case when Status = 'Homeworker' then 1 else 0 end) StatusHW,
sum(case when Status = 'Home Based' then 1 else 0 end) StatusHB,
sum(case when Status = 'PIP' then 1 else 0 end) StatusPIP,
sum(case when Status = 'TBC' then 1 else 0 end) StatusTBC
FROM HomeworkerStatus;