如何根据属性值选择前三名?

问题描述 投票:3回答:2

有一个表有4列:id,student_name,phone_num,score。我想在分数上选择TOP 3学生基础。

表:

id|student_name  |phone_num|score

1 | James        | 001350  | 89

2 | Roomi        | 123012  | 78

3 | Sibay        | 123012  | 65

4 | Ellae        | 123012  | 78

5 | Katee        | 123012  | 33

如表所示,有两个学生有相同的分数。所以他们处于同一级别。

我尝试使用'LIMIT',但它只能选择3行。

SELECT id,student_name,score
FROM table
GROUP BY id,student_name,score
ORDER BY score
LIMIT 3

预期成绩:

id|student_name  |score

1 | James        | 89

2 | Roomi        | 78

4 | Ellae        | 78

3 | Sibay        | 65

谢谢!

sql sql-server
2个回答
6
投票

你会想要使用排名功能 - 我建议密集排名。

; with CTE as 
    (Select ID, Student_Name, Score, Dense_Rank() over (order by score desc) as DR
    From Table)

Select *
from CTE
where DR <= 3

要扩展此功能:

Dense_Rank将为相关数字分配相同的数字,然后将下一个最高值分配给下一个最高数字(与Rank相比,如果存在关系则跳过排名)。例如:

Value  Rank  Dense_Rank
1      1     1
3      2     2
3      2     2
7      4     3
8      5     4

6
投票

你想在这里使用DENSE_RANK

WITH cte AS (
    SELECT id, student_name, score,
        DENSE_RANK() OVER (ORDER BY score DESC) dr
    FROM yourTable
)

SELECT id, student_name, score
FROM cte
WHERE dr <= 3
ORDER BY score DESC;

enter image description here

另一种方法,使用子查询找到前3个不同的最高分:

SELECT id, student_name, score
FROM yourTable
WHERE score IN (SELECT DISTINCT TOP 3 score FROM yourTable ORDER BY score DESC)
ORDER BY score DESC;

第二种方法类似于您尝试的方法。这是第二个查询的演示:

Demo

© www.soinside.com 2019 - 2024. All rights reserved.