想象一下下面的Player
表,其中包含字段:
PlayerId, Date, Kills and Gold
我需要在几个月内按类别(杀戮或黄金)获得球员的位置。
这是选择:
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,这不会带来正确的结果。我不想让它成为一个函数来从后端迭代几个月。我该怎么做?
最佳答案
您需要另一个用户变量来告诉您新月份的时间。
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