I have a table containing people joining and leaving an organization.
Sample data: Sql Fiddle
| pId | pName | Unit | YearIn | Yea
This should work:
WITH Years(y) AS
(
SELECT * FROM (VALUES('2013'),('2014'),('2015') ) AS tbl(y)
)
,Units AS
(
SELECT DISTINCT Unit FROM People
)
SELECT *
FROM Years CROSS JOIN Units
CROSS APPLY(SELECT (SELECT COUNT(*) FROM People AS inP WHERE inP.Unit=Units.Unit AND Years.y=inP.YearIn) AS NumIn
,(SELECT COUNT(*) FROM People AS outP WHERE outP.Unit=units.Unit AND Years.y=outP.YearOut ) As NumOut
) AS Counts
ORDER BY Years.y,Unit