Transforming rows to columns (PIVOT/CROSS TAB) and columns to rows is (UNPIVOT). Reverse operation of PIVOT is UNPIVOT.
Actual Table :
StudentName
|
Marks
|
Grade
|
A
|
10
|
I
|
B
|
20
|
II
|
C
|
40
|
IV
|
D
|
30
|
III
|
Select studentname, [I], [II], [III], [IV]
from
( Select grade, studentname, marks from tbl_student) as sourcetable
Pivot ( avg(marks) for grade in ([I],[II],[III],[IV)) as pivotable order by IV desc,III desc,II desc,I desc
from
( Select grade, studentname, marks from tbl_student) as sourcetable
Pivot ( avg(marks) for grade in ([I],[II],[III],[IV)) as pivotable order by IV desc,III desc,II desc,I desc
PIVOT Result Table :
StudentName
|
I
|
II
|
III
|
IV
|
A
|
10
| |||
B
|
20
| |||
C
|
40
| |||
D
|
30
|
Actual Table :
StudentName
|
I
|
II
|
III
|
IV
|
A
|
10
| |||
B
|
20
| |||
C
|
40
| |||
D
|
30
|
select studentname,Marks,Grade
from tbl_stdmarksdata
unpivot
(Marks for Grade in (I,II,III,IV) ) as tblunpvt
UNPIVOT Result Table :
StudentName
|
Marks
|
Grade
|
A
|
10
|
I
|
B
|
20
|
II
|
C
|
40
|
IV
|
D
|
30
|
III
|
No comments:
Post a Comment