MSSQL 行列转换

--普通版行列转换
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 (select * from tb) a pivot (max(分数) for 课程 in (语文,数学,物理)) b 
--下面这句也可以的
select * from tb pivot (max(分数) for 课程 in (语文,数学,物理)) b 

--进阶版行列转换
create table mytemp (id int,[name] varchar(10),math int,chinese int,english int)
insert into mytemp
select 1 id,'aaa' [name],'78' math,'88' chinese,'99' english union all
select 2 ,'bbb',3,5,76 union all
select 3,'ccc',6,7,8
go
select * into #temptest from (
select id,'name' kemu ,[name] fenshu from mytemp
union all 
select id,'math'  ,cast(math as varchar(10)) from mytemp
union all 
select id,'chinese'  ,cast(chinese as varchar(10)) from mytemp
union all 
select id,'english'  ,cast(english as varchar(10)) from mytemp
) tbtest
--select * from tb pivot (max(fenshu) for id in ([1],[2],[3])) b
declare @sql varchar(max)
select @sql = isnull(@sql + ',' , '') + '['+cast(id as varchar(10))+']' from mytemp
exec ('select * from #temptest pivot (max(fenshu) for id in ('+@sql+')) b')
drop table #temptest


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值