Dan Blank shows how to use the PIVOT operator in SQL Server:
I was recently approached by my firms Marketing Manager with a request for some information. She wanted to know “Which departments have our top clients never done any work for?”. For some clarity, I work in a law firm with 11 departments. The request seems pretty straightforward at first. Then once I got thinking about how the output of this report would be presented it made me reconsider quite how simple a request this was. She handed me a drawing with her vision for the output. What she wanted was :
-
Client’s names down the left,
-
List of Departments across the top,
-
Ticks and crosses at the intersection to show whether they had or had not done work for them.
You can make a good argument that presentation mechanics like this are meant for a different tool (a presentation layer) but it’s useful to know how to pivot and unpivot data within T-SQL for more reasons than just presentation.