Tuesday, 25 June 2013

SQL SERVER – PIVOT and UNPIVOT Table Examples

CREATE TABLE Product(Cust VARCHAR(25), Product VARCHAR(20), QTY INT)GO-- Inserting Data into TableINSERT INTO Product(CustProductQTY)VALUES('KATE','VEG',2)INSERT INTO Product(CustProductQTY)VALUES('KATE','SODA',6)INSERT INTO Product(CustProductQTY)VALUES('KATE','MILK',1)INSERT INTO Product(CustProductQTY)VALUES('KATE','BEER',12)INSERT INTO Product(CustProductQTY)VALUES('FRED','MILK',3)INSERT INTO Product(CustProductQTY)VALUES('FRED','BEER',24)INSERT INTO Product(CustProductQTY)VALUES('KATE','VEG',3)GO-- Selecting and checking entires in tableSELECT *FROM Product
GO
-- Pivot Table ordered by PRODUCTSELECT PRODUCTFREDKATEFROM (SELECT CUSTPRODUCTQTYFROM Productup
PIVOT 
(SUM(QTYFOR CUST IN (FREDKATE)) AS pvtORDER BY PRODUCT
GO
-- Pivot Table ordered by CUSTSELECT CUSTVEGSODAMILKBEERCHIPSFROM (SELECT CUSTPRODUCTQTYFROM Productup
PIVOT 
(SUM(QTYFOR PRODUCT IN (VEGSODAMILKBEERCHIPS)) ASpvtORDER BY CUST
GO
-- Unpivot Table ordered by CUSTSELECT CUSTPRODUCTQTYFROM(SELECT CUSTVEGSODAMILKBEERCHIPSFROM (SELECT CUSTPRODUCTQTYFROM Productup
PIVOT
SUM(QTYFOR PRODUCT IN (VEGSODAMILKBEERCHIPS)) AS pvtp
UNPIVOT
(QTY FOR PRODUCT IN (VEGSODAMILKBEERCHIPS)
AS Unpvt
GO
-- Clean up databaseDROP TABLE Product
GO

ResultSet:
-- Selecting and checking entires in table
Cust Product QTY
------------------------- -------------------- -----------
KATE VEG 2
KATE SODA 6
KATE MILK 1
KATE BEER 12
FRED MILK 3
FRED BEER 24
KATE VEG 3
-- Pivot Table ordered by PRODUCT
PRODUCT FRED KATE
-------------------- ----------- -----------
BEER 24 12
MILK 3 1
SODA NULL 6
VEG NULL 5
-- Pivot Table ordered by CUST
CUST VEG SODA MILK BEER CHIPS
------------------------- ----------- ----------- ----------- ----------- -----------
FRED NULL NULL 3 24 NULL
KATE 5 6 1 12 NULL
-- Unpivot Table ordered by CUST
CUST PRODUCT QTY
------------------------- -------- -----------
FRED MILK 3
FRED BEER 24
KATE VEG 5
KATE SODA 6
KATE MILK 1
KATE BEER 12 
12


You can see in above example where we are using the SUM aggregated functions. SUM adds up values based on column used in the sum function. In our example Kate and Veg has two entries. In our pivot example with order by Cust the values are summed up. Now when table goes under UNPIVOT operations it transforms the table which is already went under PIVOT operation.
Looking at the final PIVOT – UNPIVOT table is little different from the original table and it contains the sum of the two records which we have observed in the PIVOT table. You can see that result which are displayed in red fonts are summed.
This way we can get the original table back if aggregate functions was not applied on the data or data was in such form that aggregate function might have not made any difference.

No comments:

Post a Comment