Use PIVOT command for this:
look at this example:
SELECT s.Name ShiftName,
h.BusinessEntityID,
d.Name DepartmentName
FROM HumanResources.EmployeeDepartmentHistory h
INNER JOIN HumanResources.Department d ON
h.DepartmentID = d.DepartmentID
INNER JOIN HumanResources.Shift s ON
h.ShiftID = s.ShiftID
WHERE EndDate IS NULL AND
d.Name IN ('Production', 'Engineering', 'Marketing')
ORDER BY ShiftName
the return table of this query:
ShiftName BusinessEntityID DepartmentName
Day 3 Engineering
Day 9 Engineering
...
Day 2 Marketing
Day 6 Marketing
...
Evening 25 Production
Evening 18 Production
Night 14 Production
Night 27 Production
...
Night 252 Production
(194 row(s) affected)
now you can change the format of returned table :
SELECT ShiftName,
Production,
Engineering,
Marketing
FROM
(SELECT s.Name ShiftName,
h.BusinessEntityID,
d.Name DepartmentName
FROM HumanResources.EmployeeDepartmentHistory h
INNER JOIN HumanResources.Department d ON
h.DepartmentID = d.DepartmentID
INNER JOIN HumanResources.Shift s ON
h.ShiftID = s.ShiftID
WHERE EndDate IS NULL AND
d.Name IN ('Production', 'Engineering', 'Marketing')) AS a
PIVOT
(
COUNT(BusinessEntityID)
FOR DepartmentName IN ([Production], [Engineering], [Marketing])
) AS b
ORDER BY ShiftName
the returned table is like below:
ShiftName Production Engineering Marketing
Day 79 6 9
Evening 54 0 0
Night 46 0 0
(3 row(s) affected)