我有一张桌子'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
答案 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