PIVOT

if object_id('tb') is not null drop table tb
go
create table tb(姓名 varchar(10),课程 varchar(10),分数 int)
insert into tb values('张三','语文',74)
insert into tb values('张三','数学',83)
insert into tb values('张三','物理',93)
insert into tb values('李四','语文',74)
insert into tb values('李四','数学',84)
insert into tb values('李四','英语',94)
go
select * from tb
go
select 姓名,
max(case 课程 when '语文' then 分数 else 0 end) 语文,
max(case 课程 when '数学' then 分数 else 0 end) 数学,
max(case 课程 when '物理' then 分数 else 0 end) 物理,
max(case 课程 when '英语' then 分数 else 0 end) 英语
from tb
group by 姓名


select * from tb pivot(max(分数)for 课程 in (语文,数学,物理,英语))a
 

刚发现sql2k5 出了这个函数, 好2

原文地址:https://www.cnblogs.com/TivonStone/p/2316541.html