I have a single table 'EMPLOYEE'. I need to count the 'emp_no', so that I have a multiple columns with each aggregate based on different restrictions. Not sure how to write to get the below output.
开发者_运维技巧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
One possible answer is to use 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
精彩评论