I am trying to use dynamic pivot and need help on converting rows to columns
The table looks like:
ID expense revenue date
1 43 45 12-31-2012
1 32 32 01-01-2013
3 64 56 01-31-2013
4 31 32 02-31-2013
and I need for reporting purposes like
ID expense12-31-2012 expense01-01-2013 expense01-31-2013 revenue12-31-2013
1 43 32
3 64
In order to get both the
expense
andrevenue
columns as headers with thedate
, I would recommend applying both the UNPIVOT and the PIVOT functions.The UNPIVOT will convert the expense and revenue columns into rows that you can append the date to. Once the date is added to the column names, then you can apply the PIVOT function.
The UNPIVOT code will be:
See SQL Fiddle with Demo. This produces a result:
As you can see the expense/revenue columns are now rows with a
new_col
that has been created by concatenating the date to the end. Thisnew_col
is then used in the PIVOT:See SQL Fiddle with Demo.
The above version will work great if you have a known number of dates to turn into columns but if you have an unknown number of dates, then you will want to use dynamic SQL to generate the result:
See SQL Fiddle with Demo. Both queries generate the same result.