DECLARE @Person TABLE(person_id int null,
age int null,
gender varchar(10) null,
department_id INT null)
DECLARE @Department TABLE(
department_id INT, DepartmentName Varchar(200))
INSERT INTO @Department VALUES (1,'A')
INSERT INTO @Department VALUES (2,'B')
INSERT INTO @Department VALUES (3,'C')
INSERT INTO @Department VALUES (4,'D')
INSERT INTO @Person VALUES (1,19,'M',1)
INSERT INTO @Person VALUES (2,12,'F',1)
INSERT INTO @Person VALUES (3,30,'M',1)
INSERT INTO @Person VALUES (4,40,'F',1)
INSERT INTO @Person VALUES (5,20,'M',2)
INSERT INTO @Person VALUES (6,12,'F',2)
INSERT INTO @Person VALUES (7,30,'M',2)
INSERT INTO @Person VALUES (8,40,'F',2)
INSERT INTO @Person VALUES (9,20,'M',3)
INSERT INTO @Person VALUES (10,12,'F',3)
INSERT INTO @Person VALUES (11,30,'M',3)
INSERT INTO @Person VALUES (12,40,'F',3)
INSERT INTO @Person VALUES (13,20,'M', 4)
INSERT INTO @Person VALUES (14,12,'F',4)
INSERT INTO @Person VALUES (15,30,'M',4)
INSERT INTO @Person VALUES (16,17,'F',4)
Select D.DepartmentName ,
SUM([(Under20)Male]) [(Under20)Male],
SUM([(Under20)Female])[(Under20)Female],
SUM([Total(M)]) [Total(M)],
SUM([ Total(F)]) [ Total(F)],
SUM([Grand Total]) [Grand Total]
FROM
(
Select department_id,COUNT(*) as [(Under20)Male],0 [(Under20)Female],0 [Total(M)],0 [ Total(F)],0 [Grand Total] From @Person WHERE age<20 and gender='M' group by department_id
Union all
Select department_id,0 as [(Under20)Male],COUNT(*) [(Under20)Female],0 [Total(M)],0 [ Total(F)],0 [Grand Total] From @Person WHERE age<20 and gender='F' group by department_id
Union all
Select department_id,0 as [(Under20)Male],0 [(Under20)Female],COUNT(*) [Total(M)],0 [ Total(F)],0 [Grand Total] From @Person WHERE gender='M' group by department_id
Union all
Select department_id,0 as [(Under20)Male],0 [(Under20)Female],0 [Total(M)],COUNT(*) [ Total(F)],0 [Grand Total] From @Person WHERE gender='F' group by department_id
union all
Select department_id,0 as [(Under20)Male],0 [(Under20)Female],0 [Total(M)],0 [ Total(F)],COUNT(*) [Grand Total] From @Person group by department_id
)A
INNER JOIN
@Department D
ON A.department_id=D.department_id
GROUP BY D.DepartmentName