我有一个参与者表:
userid name
1 John
2 Sam
3 Harry
还有比赛表:
contestid contestname
1 abc
2 def
3 ghi
分数表如下所示:
id contestid userid score
1 1 1 200
2 1 2 300
3 1 3 250
4 2 1 500
5 2 2 400
6 3 2 800
现在,鉴于userid
,我需要在所有比赛中找出他的排名。
排名应基于比赛和分数。
userid=1
的输出应该是这样的:
contestid rank
1 3
2 1
3 Nil
如何获得此输出?
答案 0 :(得分:0)
1。如果您需要它按分数和竞赛排名,请尝试此
SET @rank := 0;
SET @prev := NULL;
SELECT contestid,userid,score,Rank FROM
(
SELECT contestid,userid,score,@rank := IF(@prev = contestid, @rank + 1, 1) AS rank,
@prev := contestid
FROM scores ORDER BY contestid, score DESC
) S Where userid = 1
2. 如果您需要按分数排名,请尝试此
SELECT contestid,userid,score, FIND_IN_SET( score,
(SELECT GROUP_CONCAT(score ORDER BY score DESC) FROM scores)) AS rank
FROM scores
Where UserId = 1
3. 如果您想要UserName和COntest Name,请尝试使用
SELECT C.contestname,P.name,S.score, FIND_IN_SET( S.score,
(SELECT GROUP_CONCAT(score ORDER BY score DESC) FROM scores)) AS rank
FROM scores S Join participant P ON P.userid =C.userid
Join contest C ON C.contestid = S.contestid
Where UserId = 1