操场进行比赛的各项目名称及其冠军的姓名"/>
Oracle的一道查询题——找出在同一个操场进行比赛的各项目名称及其冠军的姓名
做Oracle作业时遇到一道比较复杂的题,写个博客记录一下 ^_^
题目描述
找出在同一个操场进行比赛的各项目名称及其冠军的姓名。
本题有用到的数据库:
-
比赛项目(item)表
-
成绩(grade)表
-
运动员信息(sporter)表
解决思路
- 寻找问题的最根本、最原始子问题
- 将已查询到的表与其他已知表进行连接,进而得到接近题目要求的格式
- 如此反复,最终达到题目的要求
解决方法
- 首先将问题简化,要查询项目名称、冠军姓名,首先查询其对应的
id
- 项目号
itemid
和对应最高分(冠军)max_mark
在成绩表中可以直接通过组函数查询
select itemid, max(mark)max_mark from grade
group by itemid
查询结果:
- 根据得到的每个项目
itemid
的最高分max_mark
查询对应的运动员号sporterid
这里需要连接第二步得到的表(标记为
表a
)和成绩表grade
(记为表g
)
g.itemid = a.itemid
select g.sporterid spid,g.itemid from grade g,(
select itemid, max(mark)max_mark from grade
group by itemid) a
where g.itemid = a.itemid --表连接
and g.mark = a.max_mark --查询条件
查询结果:
- 得到上面的表之后,通过连接上表(记为
表table1
)和运动员信息表sporter
(记为表s
,获得对应冠军姓名)以及项目信息表item
(记为表i
,得到项目名称和对应所在操场)
连接方法:
table1.itemid = i.itemid
table1.spid = s.sporterid
select i.location 操场, i.itemname 项目名称, s.name 冠军姓名 from sporter s, item i,(select g.sporterid spid,g.itemid from grade g,(
select itemid, max(mark)max_mark from grade
group by itemid) a
where g.itemid = a.itemid
and g.mark = a.max_mark) table1where table1.itemid = i.itemid
and table1.spid = s.sporterid
- 最后再加上按操场名
location
排序,得到最终的答案
select i.location 操场, i.itemname 项目名称, s.name 冠军姓名 from sporter s, item i,(select g.sporterid spid,g.itemid from grade g,(
select itemid, max(mark)max_mark from grade
group by itemid) a
where g.itemid=a.itemid
and g.mark=a.max_mark) table1where table1.itemid=i.itemid
and table1.spid=s.sporterid
order by 1 desc;
查询结果:
更多推荐
Oracle的一道查询题——找出在同一个操场进行比赛的各项目名称及其冠军的姓名
发布评论