我有简单的表:
ID Score
1 90
2 85
3 96
4 96
5 73
我想获得最佳射手,所以我使用了 max 函数:
select max(s.score) as score,
s.id
from student_score as s
结果:
score id
96 1
问题是,有两个最佳射手,我要如何获得所有最佳射手?
子查询从表中获取最大分数,student_score
结果将用于比较WHERE
子句。
SELECT a.*
FROM student_score a
WHERE Score =
(
SELECT MAX(Score)
FROM student_score
)
select s.score, s.id
from student_score as s
where
s.score in
(
select max(t.score)
from student_score as t
)
如果您希望您的子查询可重用,试试这个
select s.score, s.id, m.score
from student_score as s
cross join (select max(t.score) as score from student_score as t) as m
where s.score = m.score
试试这个:
使用您的查询作为子查询从实际表中选择分数
select *
from student_score
where score in
(
select max(score)
from student_score )
Max 是一个聚合函数,只返回一行。最简单的方法是发出子查询:
SELECT * FROM student_score
WHERE score = (
SELECT MAX(score) FROM student_score
)
如果您有很多行,请确保您有一个分数索引。