Given a table like this:
[Last Name] [First Name] [DepartmentID]
---------------------------------------
Doe John 1
Doe John 2
Black Frank 3
, I'd like a result like this:
[Last Name] [First Name] [Accounting] [Management] [Development]
----------------------------------------------------------------
Doe John X X
Black Frank X
Thus far, I have a query like this:
SELECT [Last Name], [First Name], [1], [2], [3]
FROM Employees
PIVOT(SUM(DepartmentID) FOR DepartmentID IN ([1], [2], [3])
GROUP BY [Last Name], [First Name], [1], [2], [3]
Which gives me:
[Last Name] [First Name] [1] [2] [3]
----------------------------------------------------------------
Doe John 1
Doe John 2
Black Frank 3
Several problems:
- the column name comes from elsewhere, i.e. it should be derived from a function or an subquery. Can this be done?
- I assume I'll have to use dynamic SQL to get the possible departments, i.e. I can't tell
PIVOT
to simply determine all possibilities? - the column values should be just 'X' (or similar), not contain the real value. There shouldn't be multiple lines per person per possible department, which means I can't group by the pivoted columns. How do I get one line per person?
I don't really want or need to aggregate anything; I just wish to show, per department, whether the employee resides in that department. Is PIVOT
a red herring for this? I could possibly solve this in a more complicated manner with an EXISTS
statement per department?