按类别划分的球员数月

时间:2018-02-05 18:52:59

标签: mysql ranking

想象一下以下Player表,其中包含以下字段:

PlayerId, Date, Kills and Gold

我需要在几个月内按类别(杀戮或金牌)获得玩家位置。 这是SELECT:

SET @rownumber := 0;

SELECT date, rank, kills FROM (
    SELECT pla.event_date, @rownumber := @rownumber + 1 AS rank, 
    pla.kills, pla.player_id
    FROM player AS pla
    INNER JOIN ...
    WHERE.pla.event_date >= '2017-09-01' AND pla.event_date <= '2017-12-31'
    ORDER BY pla.kills DESC
) AS result WHERE player_id = 651894

当我按一个月过滤它时效果很好。 问题是@rownumber变量在下个月总是增加+1,这不会带来正确的结果。

我并不是要让它成为从后端迭代数月的函数。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您需要另一个用户变量来告诉您新月的时间。

SET @rownumber := 0;
SET @month := 0;

SELECT pla.event_date, 
  @rownumber := IF(@month=MONTH(pla.event_date), @rownumber + 1, 1) AS rank, 
  @month := MONTH(pla.event_date) AS month,
  pla.kills, pla.player_id
FROM player AS pla
INNER JOIN ...
WHERE pla.event_date >= '2017-09-01' AND pla.event_date <= '2017-12-31'
ORDER BY MONTH(pla.event_date), pla.kills DESC