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

sql行列转换

时间:2016-05-04 18:45:07      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

--行转列

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 (‘张三‘,‘语文‘,100)
insert into #Student (CName,Subject,Score) values (‘张三‘,‘数学‘,90)
insert into #Student (CName,Subject,Score) values (‘张三‘,‘英语‘,94)
insert into #Student (CName,Subject,Score) values (‘李四‘,‘语文‘,75)
insert into #Student (CName,Subject,Score) values (‘李四‘,‘数学‘,88)
insert into #Student (CName,Subject,Score) values (‘李四‘,‘英语‘,92)

select * from #Student pivot (max(Score) for Subject in ([语文],[数学],[英语])) t

结果:

技术分享

 

--列转行

if OBJECT_ID(‘tempdb..#Student‘) is not null
begin
drop table #Student
end

create table #Student
(
CName varchar(50),
[语文] int,
[数学] int,
[英语] int
)

insert into #Student (CName,[语文],[数学],[英语]) values (‘张三‘,100,90,94)
insert into #Student (CName,[语文],[数学],[英语]) values (‘李四‘,75,88,92)

select * from #Student unpivot(Score for Subject in ([语文],[数学],[英语])) t

结果:

技术分享

sql行列转换

标签:

原文地址:http://www.cnblogs.com/fengzmh/p/5459194.html

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