I have a table like this:
EmployeeID Gender Is leader Is officer
------------------------------------------
1 F
2 M Y Y
3 M
4 M
5 F Y
6 F
7 M
8 M Y
9 M Y Y
10 F
And I'd like to create a table like this:
Row_Number Category M F
------------------------------
1 Leader 2 1
2 Officer 3 0
3 Total 5 1
Using code like this:
SELECT
1 AS row_number, ' Leader' AS Category,
M+F AS Total,
SUM(IIF(Gender = 'M' AND `Is Leader` = 'Yes', 1, 0)) AS M,
SUM(IIF(Gender = 'F' AND `Is Leader` = 'Yes', 1, 0)) AS F
FROM
table
UNION
(SELECT
2 AS row_number, ' Officer' AS Category,
M+F AS Total,
SUM(IIF(Gender = 'M' AND `Is Officer` = 'Yes', 1, 0)) AS M,
SUM(IIF(Gender = 'F' AND `Is Officer` = 'Yes', 1, 0)) AS F
FROM
table
)
UNION
(SELECT
3 AS row_number, ' Total' AS Category,
M+F as Total,
SUM(IIF(Gender = 'M', 1, 0)) AS M,
SUM(IIF(Gender = 'F', 1, 0)) AS F
FROM
table
)
Is there a better way to create the table other than using UNION? Is that possible to customize groups and then do group by directly?