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

初学者求助一个动态SQL~~~
create   table   tbStudentScore(
StudentNam   varchar(10)   ,
CourseNam     varchar(40),
Score     float,
primary   key(StudentNam,CourseNam))

insert   tbStudentScore   select   '张三 ', '语文 ',78
union   all   select   '李四 ', '语文 ',82
union   all   select   '王五 ', '语文 ',74
union   all   select   '李四 ', '数学 ',98
union   all   select   '王五 ', '数学 ',65
union   all   select   '张三 ', '数学 ',31
union   all   select   '李四 ', '英语 ',56
union   all   select   '张三 ', '英语 ',88
union   all   select   '张三 ', '政治 ',73

create   table   tbStudent(
StudentID     int,
StudentNam   varchar(10))

insert   tbStudent   select   1, '张三 '
union   all   select   2, '李四 '
union   all   select   3, '王五 '
union   all   select   3, '赵六 '

要统计所有学生的成绩情况,没选某门课的分数为0
期望结果:

姓名       语文       数学     英语   政治          
张三
李四                         略
王五
赵六         0             0           0         0

----------------
我只会单表查,这是只在tbStudentScore表中统计时我写的:
请在我基础上改,这样我可以知道是哪句哪个地方起这个作用,麻烦大家了,谢谢
declare   @s   varchar(8000)
select   @s= 'select   姓名=StudentNam '
select   @s=@s+ ', '+quotename(CourseNam, ' ' ' ')+ '=sum(case   CourseNam   when   '+quotename(cast(CourseNam   as   varchar), ' ' ' ')+ '   then   Score   else   0   end)   '
                    from   tbStudentScore   group   by   CourseNam   order   by   CourseNam   desc
select   @s=@s+ '   from   tbStudentScore   group   by   StudentNam '

exec(@s)

------解决方案--------------------

declare @s varchar(8000)
select @s= 'select 姓名=b.StudentNam '
select @s=@s+ ', '+quotename(CourseNam, ' ' ' ')+ '=sum(case CourseNam when '+quotename(cast(CourseNam as varchar), ' ' ' ')+ ' then Score else 0 end) '
from tbStudentScore group by CourseNam order by CourseNam desc
select @s=@s+ ' from tbStudentScore as a right join tbStudent as b on b.StudentNam=a.StudentNam group by b.StudentNam '
exec(@s)

------解决方案--------------------
---或者这样更好理解
Declare @sql Varchar(8000)
Set @sql= ' '
Select @sql=@sql+ ',Max(Case CourseNam When ' ' '+CourseNam+ ' ' ' Then Score Else 0 End) As [ '+CourseNam+ '] '
From tbStudentScore Group By CourseNam Order By CourseNam
Print @sql
Exec( 'Select B.StudentNam '+@sql+ 'From tbStudentScore A Right Join tbStudent B On A.StudentNam=B.StudentNam Group By B.StudentNam ')