【问题标题】:How to SELECT top 3 base on an attribute value?如何根据属性值选择前 3 个?
【发布时间】:2019-04-17 15:15:49
【问题描述】:

有一个表有 4 列:id、student_name、phone_num、score。 我想根据分数选择前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

谢谢!

【问题讨论】:

  • AFAIK SQL Server 中没有 LIMIT 关键字。你确定你正确地标记了这个问题吗?

标签: sql sql-server


【解决方案1】:

您需要使用排名功能 - 我建议使用 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

【讨论】:

    【解决方案2】:

    你想在这里使用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;
    

    另一种方式,使用子查询查找前 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

    【讨论】:

    • 正准备发同样的东西,你比我快了几秒钟 :)
    • 是的,我想有一种规范的方法可以解决这个问题……就你如何给它起别名,哈哈。
    • 谢谢您,先生,这两个答案对我都有帮助。但是@APH 首先回答了这个问题,所以我将他/她的回答标记为已接受。感谢您的帮助!
    • @user8400129 不,实际上我先回答了:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多