SQL满足基于最大值的条件

时间:2017-12-21 18:49:06

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

我必须获得用户最常玩的游戏的player_id和game_code。对于每个玩家列表,他玩的游戏代码最多(不是他玩过的所有游戏)

规则:player_id是唯一的,玩家可以玩多个游戏(我想知道他玩的游戏最多)。

我尝试了max,但我只是迷失了尝试。

这是小提琴:http://sqlfiddle.com/#!9/0cf0f/2

2 个答案:

答案 0 :(得分:1)

我相信你想要这个

SELECT t.player_id, t.game_code, t.minutes_played
FROM (
      SELECT player_id, MAX(minutes_played) as maxi
      FROM play_table
      WHERE game_code in ('123','124','125','126','129')
      GROUP BY player_id
) as m
INNER JOIN play_table as t
  ON t.player_id = m.player_id and 
     t.minutes_played = m.maxi

sqlfiddle demo

答案 1 :(得分:0)

另一个答案是在正确的轨道上,但你需要在子查询中按玩家_id分组,假设你想要所有这些:

SELECT m.player_id, pt.game_code, pt.minutes_played
FROM (
    SELECT player_id, max(minutes_played) as maxi
    FROM play_table
    GROUP BY player_id
) as m
INNER JOIN play_table pt
ON  m.player_id = pt.player_id
AND pt.minutes_played = m.maxi;