码迷,mamicode.com
首页 > 数据库 > 详细

SQL行列互换很方便

时间:2015-02-26 00:00:53      阅读:305      评论:0      收藏:0      [点我收藏+]

标签:sql   行列转换   

---行转列--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

SQL行列互换很方便

标签:sql   行列转换   

原文地址:http://5090844.blog.51cto.com/5080844/1615243

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!