名人堂上的平局(团体玩家,最高水平,然后每个月的最高得分…)

6kkfgxo0  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(219)

需要列出一个名人堂的最佳球员,数据库中包含了每个单一的游戏玩家在不同的游戏。
级别具有优先级,如果级别相同,请检查最高分。
我有一个数据库,里面有用户id,等级,分数,游戏和数据。此处为架构:

CREATE TABLE IF NOT EXISTS `docs` (`user_id` int(6) unsigned NOT NULL,
`level` int(3) unsigned NOT NULL,`game` varchar(30) NOT NULL,
`score` int(5) unsigned NOT NULL,
`data` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `docs` (`user_id`, `level`, `game`, `score`,`data`) VALUES
  ('1', '7', 'pacman', '8452','2018-02-14 15:00:00'),
  ('1', '9', 'pacman', '9999','2018-02-10 16:30:00'),
  ('2', '8', 'pacman', '8500','2018-02-24 17:30:00'),
  ('1', '10', 'pacman', '9100','2018-02-15 18:30:00'),
  ('1', '10', 'pacman', '8800','2018-02-15 18:11:00'),
  ('1', '11', 'snake', '9600','2018-02-14 15:00:00'),
  ('1', '6', 'snake', '7020','2018-02-11 11:30:00'),
  ('2', '8', 'snake', '8500','2018-02-24 14:00:00'),
  ('2', '12', 'snake', '9200','2018-02-25 19:00:00'),
  ('2', '12', 'snake', '9800','2018-02-25 19:20:00'),
  ('1', '4', 'pacman', '2452','2018-03-11 15:00:00'),
  ('1', '6', 'pacman', '4999','2018-03-07 16:30:00'),
  ('2', '7', 'pacman', '5500','2018-03-02 17:30:00'),
  ('1', '7', 'pacman', '5100','2018-03-01 18:30:00'),
  ('1', '3', 'snake', '3600','2018-03-03 15:00:00'),
  ('1', '5', 'snake', '4220','2018-03-01 11:30:00'),
  ('2', '5', 'snake', '3900','2018-03-04 14:00:00'),
  ('2', '5', 'snake', '5200','2018-03-05 19:00:00');

我想为选定的月份和游戏检索名人堂,例如,如果我在三月选择吃豆人,结果应该是:

user level score
2     7    5500
1     7    5100

我试着在其他类似的主题中提出这个建议

select d1.*
from docs d1 
left outer join docs d2
on (d1.user_id = d2.user_id and d1.level < d2.level)
where d2.user_id is null
order by level desc;

但是我已经为同一个用户复制了等级,所以我不能选择游戏或者月份。
这里是sql小提琴

cx6n0qe3

cx6n0qe31#

经过长时间的工作、学习和研究,这对我来说是最好的解决方案:

SELECT user_id, level, score, game
  FROM (
            SELECT *, 
                   @rn := IF(user_id = @g, @rn + 1, 1) rn, 
                   @g := user_id
              FROM (select @g := null, @rn := 0) x, 
                   docs where game='pacman'
          ORDER BY user_id, level desc, score desc, game
       ) X
 WHERE rn = 1 order by level desc, score desc;

本主题的说明是根据其他列的顺序从组中选择一个值

w1e3prcc

w1e3prcc2#

SELECT x.* FROM docs x
JOIN 
(select user_id
      , game
      , MONTH(data) month
      , MAX(score) score
   from docs 
  where game = 'pacman' 
    and MONTH(data) = 3 
  group 
     by user_id
      , game
      , MONTH(data)
 ) y
 ON y.user_id = x.user_id
 AND y.game = x.game
 AND y.month = MONTH(x.data)
 AND y.score = x.score;

或者类似的

相关问题