--Row to column
If object_id (' tempdb.. #Student ') is not null
Begin
drop table #Student
End
CREATE TABLE #Student
(
CName varchar (50),
Subject varchar (50),
Score int
)
Insert into #Student (Cname,subject,score) VALUES (' Zhang San ', ' language ', 100)
Insert into #Student (Cname,subject,score) VALUES (' Zhang San ', ' math ', 90)
Insert into #Student (Cname,subject,score) VALUES (' Zhang San ', ' English ', 94)
Insert into #Student (Cname,subject,score) VALUES (' John Doe ', ' language ', 75)
Insert into #Student (Cname,subject,score) VALUES (' John Doe ', ' math ', 88)
Insert into #Student (Cname,subject,score) VALUES (' John Doe ', ' English ', 92)
SELECT * FROM #Student pivot (max (score) to Subject in ([Language],[Math],[English]) t
Results:
--Career change
If object_id (' tempdb.. #Student ') is not null
Begin
drop table #Student
End
CREATE TABLE #Student
(
CName varchar (50),
[Language] int,
[Math] int,
[English] int
)
Insert INTO #Student (cname,[Chinese],[Math],[English]) values (' Zhang San ', 100,90,94)
Insert INTO #Student (cname,[Chinese],[Math],[English]) VALUES (' John Doe ', 75,88,92)
SELECT * FROM #Student Unpivot (score for Subject in ([Language],[Math],[English]) t
Results:
SQL row and column conversions