查询问题排名系统MYSQL

时间:2015-04-05 11:08:54

标签: mysql sql ranking

我有一个排名系统,我会在每个游戏日保存用户排名和积分。enter image description here

现在我的问题是我想要获取用户自去年以来攀登的排名位置数。所以在这个例子中,user_id = 1从昨天起已经下降了3个位置。我当前的查询给了我一些我想要的东西,但有一些额外的计算我想删除。所以我的问题是如何计算每个用户(今天和昨天之间)的排名差异? SQL FIDDLE

3 个答案:

答案 0 :(得分:1)

SELECT current.user_id,(last.rank -current.rank)
FROM ranking as current
LEFT JOIN ranking as last ON 
last.user_id = current.user_id
WHERE current.rank_date = (SELECT max(rank_date) FROM ranking)
and
last.rank_date = (SELECT max(rank_date) FROM ranking 
 where rank_date <  (SELECT max(rank_date) FROM ranking)               
                 )

答案 1 :(得分:1)

我认为最简单的方法是:

SELECT today.user_id, (yest.rank - today.rank) as diff
FROM ranking today JOIN
     ranking yest
     on today.user_id = yest.user_id 
WHERE today.rank_date = CURRENT_DATE AND
      yest.rank_date = date_sub(CURRENT_DATE, interval 1 day);

答案 2 :(得分:0)

  

所以我的问题是我如何计算每个人的等级差异   用户(今天和昨天之间)?

关于你的sqlfiddle演示我觉得你想要这个输出:

user_id diff
1       3
1       -3
2       -1
2       -1

所以试试这个:

SELECT current.user_id,(last.rank - current.rank) as diff
FROM ranking as current
LEFT JOIN ranking as last 
ON last.rank_date = current.rank_date+1
   and last.user_id = current.user_id
where last.rank_date is not null
order by current.user_id