我有一个表A,如下所示:
name course grade
Bob C1 12
Bob C2 13
Bob C3 23
Bob C4 17
James C2 15
James C6 27
Nick C5 18
Nick C1 16
Nick C3 22
Nick C2 32
Nick C7 19
我想要一个查询,该查询可以返回与该学生的第三高年级相对应的每个学生的学生姓名和课程编号。例如,在上表中,鲍勃的第三高分是17,所以课程号是C4。同样,由于James的课程少于3门,因此不应将其课程包括在查询结果中。换句话说,查询结果应显示为:
name course_id
Bob C4
Nick C7
可以执行此操作的查询是什么?
答案 0 :(得分:2)
在标准SQL中,可以使用窗口函数来做到这一点:
select name, course
from (
select name, course, grade,
dense_rank() over (partition by name order by grade) as rnk
from grades
) t
where rnk = 3
在线示例:https://rextester.com/YOHZB50840
MySQL的在线示例:https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=3f9ff551c89f6941dbf8e424e6dfda56
答案 1 :(得分:0)
使用支持大多数dbms的相关子查询和row_number分析函数
with cte as
( select t1.* from table t1 where
exists ( select 1 from table t2 where t1.name=t2.name
group by name
having count(distinct course)>=3
)
) ,
cte2 as
(
select * ,row_number() over(partition by name order by grade asc) rn
from cte
) select * from cte2 where rn=3
答案 2 :(得分:0)
您可以尝试使用row_number()
select name, course
from (
select name, course, grade,
row_number() over (partition by name order by grade desc) as rn
from grades
) t where rn = 3