I'm using SQL Server 2008 R2 and was hoping for some help to dynamically create a column for each distinct date (month) I have in my dataset, where I can SUM the quantity per month by user. So for example my data looks like:
Emp Month QTY
-------------------------
John 3/1/2016 20
John 3/1/2016 30
John 4/1/2016 15
John 6/1/2016 40
Jim 2/1/2016 25
Jim 4/1/2016 28
Jim 5/1/2016 15
Jim 5/1/2016 15
Jim 6/1/2016 32
Alex 4/1/2016 20
Alex 4/1/2016 20
Alex 4/1/2016 20
Alex 5/1/2016 45
and I'd like to just get the totals per month by Emp
, like this:
Employee 2/1/2016 3/1/2016 4/1/2016 5/1/2016 6/1/2016
--------------------------------------------------------------------
John 0 50 15 0 40
Jim 25 0 28 30 32
Alex 0 0 60 45 0
I've seen some PIVOT
and CROSS APPLY
functions where the columns (month in this case) are specified and hardcoded before hand. Is there an easy way to dynamically create those column names based on the values within [Month]
?
Either way, any help is greatly appreciated.