日期:2014-05-19  浏览次数:20376 次

求教一个行转列的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

/*
1 Mike 123@163.com 美术 90 数学 98 政治 89 NULL NULL NULL NULL NULL NULL
2 Tom 456@sina.com 美术 69 数学 77 NULL NULL NULL NULL NULL NULL NULL NULL
3 Bill bill@yahoo.com.cn 历史 98 美术 99 数学 87 英语 88 语文 69 政治 100
*/