Monday, February 13, 2012

SQL Server PIVOT and UNPIVOT to transpose a table


I had to rotate/transpose a SQL table variable for reporting purposes and eventually got SQL Server 2008 PIVOT and UNPIVOT operators to achieve this (rather that using a longer UNION ALL approach.)

Source table definition:
DECLARE @ResultTable TABLE
(
Ordinal INT,
Calc1 FLOAT,
Calc2 FLOAT,
Calc3 FLOAT
)

SELECT * FROM @ResultTable:
1 | 1000000 | 0.438556290234799 | 3.53674427608709
2 | 0 | 0.877112580469597 | 7.07348855217417
3 | 1000000 | 0.877112580469597 | 7.07348855217417
4 | 0 | 1.3156688707044 | 10.6102328282613
5 | 1000000 | 1.3156688707044 | 10.6102328282613
6 | 0 | 0 | 0

SQL to rotate/transpose rows to columns:
;WITH CTE AS 
  (
    SELECT Ordinal, Col1 as SeriesName, Col as Value FROM (SELECT * FROM @ResultTable) P
      UNPIVOT (Col FOR Col1 IN (
        Calc1, Calc2, Calc3 -- Series to return as rows
      )) UN
  )
  SELECT * FROM CTE
    PIVOT 
    (MAX(value) FOR Ordinal IN (
      [1],[2],[3],[4],[5],[6]  -- Ordinals to return as columns
    )) PVT

Transposed table results:
Calc1 | 1000000 | 0 | 1000000 | 0 | 1000000 | 0
Calc3 | 3.53674427608709 | 7.07348855217417 | 7.07348855217417 | 10.6102328282613 | 10.6102328282613 | 0
Calc2 | 0.438556290234799 | 0.877112580469597 | 0.877112580469597 | 1.3156688707044 | 1.3156688707044 | 0

Note that the limitation with this solution is the number rows in source table/columns in transposed table is fixed and requires SQL Server 2005+


No comments:

Post a Comment