找到每个组的最高n值

时间:2012-09-12 05:58:50

标签: mysql sql greatest-n-per-group

我遇到了与此Finding the highest n values of each group in MySQL

相同的问题

我有一些这样的数据:

+ --------- + ----------- +
| lane      | series      |
+ --------- + ----------- +
| 1         | 680         |
| 1         | 685         |
| 1         | 688         |
| 2         | 666         |
| 2         | 425         |
| 2         | 775         |
+ --------- + ----------- +

而且我想获得每个泳道最高的n系列(为了这个例子,我们说2个,但它可能比这更多) 所以输出应该是:

+ --------- + ----------- +
| lane      | series      |
+ --------- + ----------- +
| 1         | 688         |
| 1         | 685         |
| 2         | 775         |
| 2         | 666         |
+ --------- + ----------- +

我认为带有“时髦”MySQL功能的SQL非常好用。

set @count:=-1, @lane:=0; 
select lane, series
from (select lane, series from lane_series order by lane, series desc) x
where if(lane != @lane, @count:=-1, 0) is not null
and if(lane != @lane, @lane:=lane, lane) is not null
and (@count:=@count+1) < 2; -- Specify the number of row at top of each group here

令我惊讶的是,它在MySQL 5.0和MySQL 5.1上运行良好,但它不适用于我的生产MySQL版本的MySQL 5.5。

MySQL 5.5的结果是这样的:

+ --------- + ----------- +
| lane      | series      |
+ --------- + ----------- +
| 1         | 688         |
| 1         | 685         |
+ --------- + ----------- +

请帮助我让它在MySQL 5.5上运行或告诉我为什么结果不同,非常感谢!

更新: 因为我的生产数据库中有大约300万条记录,所以我想知道如何以尽可能快的速度快速获得结果。

1 个答案:

答案 0 :(得分:5)

尝试这个,也许它适合你。

SELECT lane, series
FROM   tableA
WHERE (
        SELECT count(*)
        FROM   tableA AS f
        WHERE  f.lane = tableA.lane AND 
               f.series >= tableA.series
      ) <= 2
ORDER BY lane, series DESC

SQLFiddle Demo

相关问题