Pivot provides an easy mechanism in Sql Server to transform rows into columns.
Unpivot is the reversal of the Pivot operation. It basically provides a mechanism for transforming columns into rows.
Example
-- Creating Test Table
CREATE TABLE Example(Cust VARCHAR(25), Product VARCHAR(20), QTY INT)
GO
-- Inserting Data into Table
INSERT INTO Example(Cust, Product, QTY)
VALUES('KATE','VEG',2)
INSERT INTO Example(Cust, Product, QTY)
VALUES('KATE','SODA',6)
INSERT INTO Example(Cust, Product, QTY)
VALUES('KATE','MILK',1)
INSERT INTO Example(Cust, Product, QTY)
VALUES('KATE','BEER',12)
INSERT INTO Example(Cust, Product, QTY)
VALUES('FRED','MILK',3)
INSERT INTO Example(Cust, Product, QTY)
VALUES('FRED','BEER',24)
INSERT INTO Example(Cust, Product, QTY)
VALUES('KATE','VEG',3)
GO
-- Selecting and checking entires in table
SELECT * FROM Example
GO
-- Pivot Table ordered by CUST
SELECT CUST, VEG, SODA, MILK, BEER, CHIPS
FROM (
SELECT CUST, PRODUCT, QTY
FROM Example) up
PIVOT (SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt
ORDER BY CUST
GO
-- Unpivot Table ordered by CUST
SELECT CUST, PRODUCT, QTY
FROM
(
SELECT CUST, VEG, SODA, MILK, BEER, CHIPS
FROM (
SELECT CUST, PRODUCT, QTY
FROM Example) up
PIVOT
( SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt) p
UNPIVOT
(QTY FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)
) AS Unpvt
GO
-- Clean up database
DROP TABLE Example
GO