Search This Blog

Monday, August 29, 2011

The UNPIVOT operator performs the reverse operation of PIVOT, by rotating columns into rows.


The UNPIVOT operator performs the reverse operation of PIVOT, by rotating columns into rows.

Sample Denormalized Table
CREATE TABLE #Student
(
StudentID int ,
Marks1 float,
Marks2 float,
Marks3 float
)

INSERT INTO #Student VALUES (1, 5.6, 7.3, 4.2)
INSERT INTO #Student VALUES (2, 4.8, 7.9, 6.5)
INSERT INTO #Student VALUES (3, 6.8, 6.6, 8.9)
INSERT INTO #Student VALUES (4, 8.2, 9.3, 9.1)
INSERT INTO #Student VALUES (5, 6.2, 5.4, 4.4)

SELECT * FROM #Student
SELECT StudentID, MarksNo, MarksRecd
FROM
(SELECT StudentID,
Marks1, Marks2, Marks3
FROM #Student) stu
UNPIVOT
(MarksRecd FOR MarksNo IN (Marks1, Marks2, Marks3)
) AS mrks

No comments:

Post a Comment