首页 > 代码库 > 列转行且行转列

列转行且行转列

原数据格式如下:

这是学生的成绩表,每科为一列,要求转换为下面的格式:

即,把把课程列转换为行,把学生行转换为列:

建表:

create table #a
(name varchar(20),english int,chinese int ,math int)
insert into #a values( ‘zhangsan‘,10,39,40)
insert into #a values( ‘lisi‘,16,25,36)

 

思路:先把列转换为行:

select name,km,score
from
(select name,english,chinese,math
from #a) a
UNPIVOT
(score for km in
(english,chinese,math )
)
as unpvt

如下数据:

 

然后把行name转换为列:

select *
from
(

select name,km,score from

(select name,km,score from (select name,english,chinese,math from #a) a UNPIVOT (score for km in (english,chinese,math ) ) as unpvt) a

) a

PIVOT
(max(score) for name in (zhangsan,lisi))
as unpvt