从一个表输出多个聚合

时间:2011-08-10 15:24:31

标签: calculated-columns

我有一张桌子'EMPLOYEE'。我需要计算'emp_no',以便根据不同的限制我有多个列,每个聚合。不知道如何写以获得以下输出。

SELECT DEP_NO, COUNT(EMP_NO) Active
FROM EMPLOYEE
WHERE STATUS = 'active'

SELECT DEP_NO, COUNT(EMP_NO) "On Leave"
FROM EMPLOYEE
WHERE STATUS = 'on leave'


dep_no| Active  On Leave Female  Male
------|------------------------------
 1    |  236      10      136    100
 2    |  500      26      250    250
 3    |  130       2       80     50
 4    |  210       7       60    150

1 个答案:

答案 0 :(得分:0)

一个可能的答案是使用SUM + CASE

SELECT DEP_NO, SUM(CASE WHEN STATUS = 'active' THEN 1 ELSE 0 END) AS Active, 
               SUM(CASE WHEN STATUS = 'on leave' THEN 1 ELSE 0 END) AS [On Leave], 
               SUM(CASE WHEN STATUS = 'female' THEN 1 ELSE 0 END) AS Female,
               SUM(CASE WHEN STATUS = 'male' THEN 1 ELSE 0 END) AS Male
FROM EMPLOYEE
GROUP BY DEP_NO