在SQL中,如何为每个组选择前2行

2021-11-20 00:00:00 sql group-by mysql greatest-n-per-group

我有一个表格如下:

NAME    SCORE
-----------------
willy       1
willy       2
willy       3
zoe         4
zoe         5
zoe         6

这是示例

group by 的聚合函数只允许我得到每个name 的最高分.我想查询每个 name 的最高 2 分,我该怎么做?

The aggregation function for group by only allow me to get the highest score for each name. I would like to make a query to get the highest 2 score for each name, how should I do?

我的预期输出是

NAME    SCORE
-----------------
willy       2
willy       3
zoe         5
zoe         6

推荐答案

SELECT *
FROM   test s
WHERE 
        (
            SELECT  COUNT(*) 
            FROM    test  f
            WHERE f.name = s.name AND 
                  f.score >= s.score
        ) <= 2

  • SQLFiddle 演示

相关文章