28 Sept 2011

Pivot and Unpivot in SQL Server

SELECT Company,A,B
FROM   (SELECT 'CG1' Company,'A' Product,1 Quantity
        UNION
        SELECT 'CG1','B',2
        UNION
        SELECT 'CG1','A',3
        UNION
        SELECT 'CG1','B',4
        UNION
        SELECT 'CG2','A',1
        UNION
        SELECT 'CG2','B',2
        UNION
        SELECT 'CG2','A',3
        UNION
        SELECT 'CG2','B',4) AS MainTable1
PIVOT (sum(Quantity) FOR Product IN (A, B)) AS PivotTable

-----------------------------------------------------------

SELECT Company,Product,Quantity
FROM   (SELECT 'CG1' Company,1 Product1,2 Product2,3 Product3
        UNION
        SELECT 'CG2',2,3,4
        UNION
        SELECT 'CG3',4,2,5) mainTable
UNPIVOT ( Quantity FOR Product IN (Product1, Product2, Product3) ) AS unpivottable

No comments:

Post a Comment