0

我有简单的表:

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

问题是,有两个最佳射手,我要如何获得所有最佳射手?

4

4 回答 4

5

子查询从表中获取最大分数,student_score结果将用于比较WHERE子句。

SELECT a.*
FROM student_score a
WHERE Score = 
(
    SELECT MAX(Score)
    FROM student_score
)
于 2012-10-30T08:22:35.277 回答
3
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

SQL 提琴示例

于 2012-10-30T08:21:59.287 回答
2

试试这个:

使用您的查询作为子查询从实际表中选择分数

select * 
from  student_score 
where score in
 (
    select max(score)
    from   student_score )


SQL Fiddle 演示

于 2012-10-30T08:22:33.970 回答
1

Max 是一个聚合函数,只返回一行。最简单的方法是发出子查询:

SELECT * FROM student_score
WHERE score = (
    SELECT MAX(score) FROM student_score
)

如果您有很多行,请确保您有一个分数索引。

于 2012-10-30T08:22:21.593 回答