2015-04-05 114 views
0

我有一個排名系統,我保存每個遊戲日的用戶排名和積分。 enter image description here查詢問題排名系統MYSQL

現在我的問題是,我想獲取用戶自上一天以來攀升的排名位置數。所以在這個例子中,user_id = 1自昨天以來已經下降了3個倉位。我目前的查詢給了我一些我想要的,但有一些額外的計算,我想刪除。所以我的問題是我如何計算每個用戶(今天和昨天之間)的排名差異? SQL FIDDLE

+0

你想僅比較「今日」和「昨天」*(3月17日和3月16日)*?或者你希望表中的每一行與前一天相比較?每個用戶每天都有記錄嗎,還是會有差距? – MatBailie 2015-04-05 11:49:31

+1

您還需要將'current.user_id = last.user_id'添加到您的SQL *(作爲'LEFT JOIN'的一部分)*。 – MatBailie 2015-04-05 11:51:52

+0

不,我只是想今天與昨天比較這個查詢。是的,每個用戶每天都會有一個記錄 – Rocksteady 2015-04-05 12:20:39

回答

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)    
       ) 
+0

您是否看過OPS SQLFiddle示例? – MatBailie 2015-04-05 11:47:34

+0

我通過編輯小提琴做了這個。 – 2015-04-05 11:55:52

+0

謝謝@JoshuaByer這就是我一直在尋找的! – Rocksteady 2015-04-05 12:17:18

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 
+0

'ON last.rank_date = current.rank_date + 1'應該是'-1'以獲得「上一個日期」 – MatBailie 2015-04-05 12:08:52

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);