【SQL】——行列转换


/*
源成绩表结构
StuName              cid         score
-------------------- ----------- -----------
Ranen                1           80
Ranen                2           84
Ranen                3           98
kevin                1           74
kevin                2           98
kevin                3           100
jacky                1           50
jacky                3           96

源课程表结构
ID          cName
----------- ------------------------------
1           C#
2           javascript
3           Sql Server

转换后表结构
StuName              C#          javascript  Sql Server
-------------------- ----------- ----------- -----------
jacky                50          NULL        96
kevin                74          98          100
Ranen                80          84          98

*/

Create Table CourseTable
(
 ID int identity primary key,
 cName nvarchar(30) not null
)
go
insert into CourseTable values('C#')
insert into CourseTable values('javascript')
insert into CourseTable values('Sql Server')

create table ScoreTable
(
 StuName varchar(20) not null,--学生
 cid int,--课程编号
 score int --成绩
)
go
insert into ScoreTable values('Ranen',1,80)
insert into ScoreTable values('Ranen',2,84)
insert into ScoreTable values('Ranen',3,98)
insert into ScoreTable values('kevin',1,74)
insert into ScoreTable values('kevin',2,98)
insert into ScoreTable values('kevin',3,100)
insert into ScoreTable values('jacky',1,50)
insert into ScoreTable values('jacky',3,96)
go
--2000 静态行列转
select StuName,
max(case cname when 'C#' then Score else 0 end) C#,
max(case cname when 'javascript' then Score else 0 end) javascript,
max(case cname when 'Sql Server' then Score else 0 end) SqlServer
 from (
select s.StuName,c.cName,s.Score from ScoreTable s
inner join CourseTable c on s.cid=c.id) T group by StuName

--2000 动态SQL
--insert into CourseTable values('html') --添加一门课程测试动态SQL
declare @sql varchar(500)
set @sql = 'select StuName'
select @sql = @sql + ' , max(case cname when '''+cName+''' then Score else 0 end) ['+cName+']'
from (select distinct cName from CourseTable) as c
set @sql = @sql + ' from  (select s.StuName,c.cName,s.Score from ScoreTable s
       inner join CourseTable c on s.cid=c.id) T group by StuName'

exec(@sql)
go


--2005 静态SQL
select * from (
 select s.StuName,c.cName,s.Score from ScoreTable s
 inner join CourseTable c on s.cid=c.id
) a pivot (max(Score) for cName in (C#,javascript,[Sql Server])) b

--2005 动态SQL
declare @sql varchar(500)
select @sql = isnull(@sql + ',' , '') + '['+cname+']' from CourseTable group by cName
exec ('select * from (
 select s.StuName,c.cName,s.Score from ScoreTable s
 inner join CourseTable c on s.cid=c.id
) a pivot (max(Score) for cName in (' + @sql + ')) b')
go
drop table CourseTable
drop table ScoreTable
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值