I have read dozens of solutions to similar transposition problems as the one I am about to propose but oddly none that exactly mirrors my issue. I am simply trying to flip my rows to columns in a simple dashboard type data set.
The data when pulled from various transaction tables looks like this:
DatePeriod PeriodNumberOverall Transactions Customers Visits
'Jan 2012' 1 100 50 150
'Feb 2012' 2 200 100 300
'Mar 2012' 3 300 200 600
and I want to be able to generate the following:
Jan 2012 Feb 2012 Mar 2012
Transactions 100 200 300
Customers 50 100 200
Visits 150 300 600
The metrics will be static (Transactions, Customers and Visits), but the date periods will be dynamic (IE - more added as months go by).
Again, I have ready many examples leveraging pivot, unpivot, store procedures, UNION ALLs, etc, but nothing where I am not doing any aggregating, just literally transposing the whole output. I have also found an easy way to do this in Visual Studio 2005 using a matrix with an embedded list, but I can't export the final output to excel which is a requirement. Any help would be greatly appreciated.
If you can know how many different date period in advance, then you can use fixed query like following:
SQL FIDDLE DEMO
If how many date period is unpredictable, then @Alexander already gave the solution, the following code is just a second opinion, instead of using APPLY, using UNION ALL
SQL FIDDLE DEMO
You need to dynamically create a SQL statement with PIVOT and APPLY operators on the fly and then run that command. If your metrics static(Transactions, Customers and Visits), hence we can use CROSS APPLY operator with VALUES As a Table Source.
For SQL Server2008+
Result:
Demo on SQLFiddle
For SQL Server 2005
In order to get the result that you want you need to first
UNPIVOT
the data and thenPIVOT the
DatePeriod` Values.The UNPIVOT will transform the multiple columns of
Transactions
,Customers
andVisits
into multiple rows. The other answers are using aUNION ALL
to unpivot but SQL Server 2005 was the first year theUNPIVOT
function was supported.The query to unpivot the data is:
See Demo. This transforms your current columns into multiple rows, so the data looks like the following:
Now, since the data is in rows, you can apply the
PIVOT
function to theDatePeriod
column:See SQL Fiddle with Demo.
If you have an unknown number of date period's then you will use dynamic SQL:
See SQL Fiddle with Demo. Both will give the result: