---行转列--pivot
create table tempTable
(
id int primary key identity(1,1),
Student nvarchar(36),
[Subject] nvarchar(36),
Score int,
)
select * from tempTable
insert into tempTable values (‘张三‘,‘语文‘,‘90‘)
insert into tempTable values (‘张三‘,‘语文‘,‘89‘)
insert into tempTable values (‘李四‘,‘语文‘,‘90‘)
insert into tempTable values (‘王五‘,‘语文‘,‘93‘)
insert into tempTable values (‘张三‘,‘数学‘,‘89‘)
insert into tempTable values (‘李四‘,‘数学‘,‘79‘)
insert into tempTable values (‘王五‘,‘数学‘,‘88‘)
insert into tempTable values (‘张三‘,‘英语‘,‘87‘)
insert into tempTable values (‘李四‘,‘英语‘,‘94‘)
insert into tempTable values (‘王五‘,‘英语‘,‘96‘)
select Student,sum(语文)as 语文,sum(数学) as 数学,sum(英语) as 英语 into tempsubject from tempTable pivot(avg(Score) for [Subject] in (语文,数学,英语)) as A group by Student order by 语文 desc
---列转行unpivot
select * from tempsubject
unpivot
(
Score for [Subject] in(语文,数学,英语)
)
as f
本文出自 “倔強的蝸牛” 博客,请务必保留此出处http://5090844.blog.51cto.com/5080844/1615243
原文地址:http://5090844.blog.51cto.com/5080844/1615243