求教大家一个交叉表查询sql写法

s54092447 2008-05-23 11:41:07
写查询软件的时候遇到一个难题,有句sql语句写不出来,希望得到各位前辈指点.
我简化后大致是这样的:
一个成绩表(scores),有3个字段:姓名(name),学科号(subject_no),成绩(score).
数据如下:
小明,01,80
小明,02,70
小红,01,90
小红,02,75

还有一个学科表(subjects),有2个字段:学科号(subject_no),学科名称(subject_name)
数据如下:
01,语文
02,数学

现在要求查询出这样一个结果:
语文 数学
小明: 80 70
小红: 90 75

发现必须使用交叉表,使用的sql语句为:
select a.name,
sum(case b.subject_name when '语文' then score else 0 end) as 语文,
sum(case b.subject_name when '数学' then score else 0 end) as 数学
from scores a, subjects b
where a.subject_no = b.subject_no
group by 1 order by 1

但是现在有新要求了,说学科数不能写死了,可能以后subjects还会插入(03,英语)等等.
要求以后查询出来的结果,可以动态的根据学科表里的学科数增加.
比如增加了(03,英语),就要求查出来是这样的样式:
语文 数学 英语
小明: 80 70 50
小红: 90 75 99

反正不能因为增加了学科数而去改动sql语句,要求现在的sql语句可以满足这样的动态查询要求.
实在想不出该怎么做了,求教各位大侠,不胜感激.
...全文
198 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
-狙击手- 2008-05-25
  • 打赏
  • 举报
回复
。。。
中国风 2008-05-25
  • 打赏
  • 举报
回复

declare @s nvarchar(4000)
set @s=''
select
@s=@s+','+quotename(subject_name)+'=sum(case when subject_no='+quotename(subject_no,'''')+' then score else 0 end)'
from
subjects
set @s=stuff(@s,1,1,'')
exec('select Name,'+@s+ ' from scores group by name')
新鲜鱼排 2008-05-25
  • 打赏
  • 举报
回复
http://topic.csdn.net/t/20061010/21/5073353.html
dawugui 2008-05-23
  • 打赏
  • 举报
回复
其他方法见:
http://topic.csdn.net/u/20080512/14/6022944a-0b8b-4239-9f2b-9d2a2492d93d.html
dawugui 2008-05-23
  • 打赏
  • 举报
回复
select a.name,
max(case b.subject_name when '语文' then a.score else 0 end) 语文,
max(case b.subject_name when '数学' then a.score else 0 end) 数学,
max(case b.subject_name when '英语' then a.score else 0 end) 英语
from scores a , subjects b
where a.subject_no = b.subject_no
group by a.name
华芸智森 2008-05-23
  • 打赏
  • 举报
回复
http://topic.csdn.net/u/20080505/10/95d1a27d-345d-42b1-a362-1d2156c8d6f5.html

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧