/*
源成绩表结构
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