MySQL中每个id的前N行

时间:2015-08-05 19:35:06

标签: mysql sql group-by aggregate

我的用户分数表是这样的:

id | kills
----------
2  | 1
1  | 1
1  | 5
1  | 3
2  | 4
2  | 5
3  | 5

我想获得每个玩家的前2行,其中有2次以上的杀戮。所以结果应该是这样的

id | kills
----------
1  | 5
1  | 3
2  | 4
2  | 5
3  | 5

我试过了,但它没有用:

SELECT * 
FROM user_stats us 
WHERE 
(
    SELECT COUNT(*) 
    FROM user_stats f 
    WHERE f.id=us.id AND f.kills > 2
) <= 2;

4 个答案:

答案 0 :(得分:0)

select * from user_stats
where (id,kills) in (select id, max(kills) from user_stats where kills > 2 group by id
                    union
                    select id, min(kills) from user_stats where kills > 2 group by id)

答案 1 :(得分:0)

我怀疑你只想要杀死&gt;的用户的两个最大值? 2.如果是,请使用变量:

select us.*
from (select us.*,
             (@rn := if(@i = id, @rn + 1,
                        if(@i := id, 1, 1)
                       )
             ) as seqnum
      from user_stats us cross join
           (select @rn := 0, @i := -1) params
      where us.kills > 2
      order by us.id, kills desc
     ) us
where seqnum <= 2;

答案 2 :(得分:0)

试试这个。我来自Oracle,其中rownum是所选行数。这应该具有相同的效果。

select @rownum:=@rownum+1, us.*
from user_stats us , (select @rownum := 0) r
where id in (
    select id from user_stats f 
    group by id 
    having count(*) > 2
)
and @rownum < 3;

答案 3 :(得分:0)

基于vkp的响应。当id超过1 kill

时,取最小值和最大值
select id, max(kills) 
  from user_stats 
  group by id 
  having count(kills) > 2 
union 
select id, min(kills) 
  from user_stats 
  group by id 
  having count(kills) > 2 
order by id