有一个表有 4 列:id、student_name、phone_num、score。
我想根据分数选择前3名的学生。
table :
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
如表所示,有两个学生的分数相同。
所以他们处于同一级别。
我尝试使用“限制”,但它只能选择 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
谢谢!
最佳答案
你会想要使用排名功能 - 我推荐 Dense Rank。
; 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
关于sql - 如何根据属性值选择前 3 个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55730956/