In SQL, how to select the top 2 rows for each group(在SQL中,如何为每个组选择前2行)
问题描述
我有一个表格如下:
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 演示
这篇关于在SQL中,如何为每个组选择前2行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!