开发者

Output Multiple Aggregates From One Table

开发者 https://www.devze.com 2023-03-27 06:49 出处:网络
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

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号