我有一个表,studentMark 学生成绩表
他的结构为:
自增ID ,学生ID, ,科目ID, 成绩分数 ,考试时间 ,考试标识ID
ID (int ),StudentID( int ), Kind(int ), Mark( float ) ,TestTime (DateTime), TestKindID(int)
1, ,20, ,1 ,90 ,2004-05-06 , 1
2, ,20, ,2 ,80 ,2004-05-06 , 1
3, ,20, ,3 ,70 ,2004-05-06 , 1
4, ,21, ,1 ,60 ,2004-05-06 , 1
5, ,21, ,2 ,70 ,2004-05-06 , 1
6, ,21, ,3 ,90 ,2004-05-06 , 1
7, ,23, ,1 ,50 ,2004-05-06 , 1
8, ,23, ,2 ,40 ,2004-05-06 , 1
9, ,23, ,3 ,20 ,2004-05-06 , 1
10, ,20, ,1 ,90 ,2004-02-26 , 2
11, ,20, ,2 ,80 ,2004-02-26 , 2
12, ,20, ,3 ,70 ,2004-02-26 , 2
13, ,21, ,1 ,60 ,2004-02-26 , 2
14, ,21, ,2 ,70 ,2004-02-26 , 2
14, ,21, ,3 ,90 ,2004-02-26 , 2
15, ,23, ,1 ,50 ,2004-02-26 , 2
16, ,23, ,2 ,40 ,2004-02-26 , 2
17, ,23, ,3 ,20 ,2004-02-26 , 2
我现在想用SQL 语句得到这样的结果,(也就是要把一次考试的所有科目成绩,和科目名称放在同一行来显示,而科目的多少是不定的,可能有N个)请问怎么做?
学生编号,科目,分数,科目,分数,科目,分数,考试标识
20 , 1 , 90 , 2 , 80 , 2 , 70 , 1
21 , 1 , 60 , 2 , 70 , 3 , 90 , 1
21 , 1 , 50 , 2 , 40 , 3 , 20 , 1
20 , 1 , 90 , 2 , 80 , 3 , 70 ,2
21 , 1 , 60 , 2 , 70 , 3 , 90 , 2
21 , 1 , 50 , 2 , 40 , 3 , 20, 2
如果科目很多话,就像下面这样一直增出来
21 , 1 , 50 , 2 , 40 , 3 ,13 , 4 ,55 , 5 ,66 ,6 ,20 ....... 2
16
15楼 zjcxc (邹建)
回复于 2005-05-23 12:04:11 得分 0
--测试
--测试数据
create table studentMark(ID int,StudentID int,Kind int,Mark float,TestTime DateTime,TestKindID int)
insert studentMark select 1, 20,1, 90,'2004-05-06',1
union all select 2, 20,2, 80,'2004-05-06',1
union all select 3, 20,3, 70,'2004-05-06',1
union all select 4, 21,1, 60,'2004-05-06',1
union all select 5, 21,2, 70,'2004-05-06',1
union all select 6, 21,3, 90,'2004-05-06',1
union all select 7, 23,1, 50,'2004-05-06',1
union all select 8, 23,2, 40,'2004-05-06',1
union all select 9, 23,3, 20,'2004-05-06',1
union all select 10, 20,1, 90,'2004-02-26',2
union all select 11, 20,2, 80,'2004-02-26',2
union all select 12, 20,3, 70,'2004-02-26',2
union all select 13, 21,1, 60,'2004-02-26',2
union all select 14, 21,2, 70,'2004-02-26',2
union all select 14, 21,3, 90,'2004-02-26',2
union all select 15, 23,1, 50,'2004-02-26',2
union all select 16, 23,2, 40,'2004-02-26',2
union all select 17, 23,3, 20,'2004-02-26',2
go
--查询
declare @s nvarchar(4000)
set @s=''
select @s=@s
+','+quotename(rtrim(Kind)+'科目')+'='+quotename(Kind,'''')
+','+quotename(rtrim(Kind)+'分数')+'=max(case Kind when '+quotename(Kind,'''')
+' then Mark end)'
from studentMark
group by Kind
exec('select StudentID'+@s+',TestKindID
into ## from studentMark
group by StudentID,TestKindID
order by StudentID,TestKindID')
select * from ##
drop table ##
go
--删除测试
drop table studentMark