首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求教一个行转列的SQL语句有关问题

2012-04-12 
求教一个行转列的SQL语句问题有两个表:表A包含ID、姓名、Email等基本信息表B包含每人人选的课和成绩(ID、课程

求教一个行转列的SQL语句问题
有两个表:
表A包含ID、姓名、Email等基本信息
表B包含每人人选的课和成绩(ID、课程、成绩),每个人可能有0到6条
【注意课程很多,远远大于6种】

现在要输出的结构是:
ID、姓名、Email、课程1、成绩1、课程2、成绩2、课程3、成绩3、课程4、成绩4、课程5、成绩5、课程6、成绩6

求教怎么写查询?
存储过程或者借助临时表都行!

[解决办法]
create table A(ID int,姓名 varchar(20),Email varchar(100))
create table B(ID int,课程 varchar(20),成绩 int)
insert A select 1, 'Mike ', '123@163.com '
union all select 2, 'Tom ', '456@sina.com '
union all select 3, 'Bill ', 'bill@yahoo.com.cn '

insert B select 1, '数学 ',98
union all select 1, '政治 ',89
union all select 1, '美术 ',90

union all select 2, '数学 ',77
union all select 2, '美术 ',69

union all select 3, '数学 ',87
union all select 3, '语文 ',69
union all select 3, '英语 ',88
union all select 3, '政治 ',100
union all select 3, '历史 ',98
union all select 3, '美术 ',99

declare @s varchar(8000)
set @s= ' '
select @s=@s+ ',max(case bh when ' ' '+rtrim(bh)+ ' ' ' then 课程 else null end) as 课程 '+rtrim(bh)+ '
,max(case bh when ' ' '+rtrim(bh)+ ' ' ' then 成绩 else null end) as 成绩 '+rtrim(bh)+ ' '
from (select *,bh=(select count(1) from B where ID=b1.ID and 课程 <=b1.课程) from B b1)t group by bh

select @s= 'select A.ID,A.姓名,A.Email, '+stuff(@s,1,1, ' ')+ ' from A inner join
(select *,bh=(select count(1) from B where ID=b1.ID and 课程 <=b1.课程) from B b1)t
on A.ID=t.ID group by
A.ID,A.姓名,A.Email '

exec(@s)

drop table A,B

/*
1Mike123@163.com美术90数学98政治89NULLNULLNULLNULLNULLNULL
2Tom456@sina.com美术69数学77NULLNULLNULLNULLNULLNULLNULLNULL
3Billbill@yahoo.com.cn历史98美术99数学87英语88语文69政治100
*/

热点排行