我知道一点SQL,我一直想知道如何从我的Users
表中选择用户,我发现了这个:
SELECT *, FIND_IN_SET( Score, (
SELECT GROUP_CONCAT( Score ORDER BY Score DESC )
FROM Users
)
) AS Rank
FROM Users
WHERE UserID = 100
ORDER BY Score DESC
问题在于,如果同一用户有多行,那么它们将单独排名。我想知道如何获得最高Score
并让Rank
返回
它看起来像什么(没有WHERE UserID = 100
子句):
ID-----UserID-----Score----Rank
1------100--------6--------1
2------192--------4--------2
3------192--------3--------3
我想要的(没有WHERE UserID = 100
子句):
ID-----UserID-----Score----Rank
1------100--------6--------1
2------192--------4--------2
3------192--------3--------2
感谢您的帮助!
答案 0 :(得分:1)
尝试以下方法:
SET @rank=0;
SELECT *, @rank:=@rank+1 AS rank
FROM Users
WHERE UserID = 100
ORDER BY Score DESC
答案 1 :(得分:0)
使用GROUP BY(UserID)
与MAX(Score)
获得maxScore
,然后排名。
(作为OP希望每一行用户,但只有最佳排名我们添加INNER JOIN
)
SELECT TM.`UserID`, TM.`Score`, T3.`rank`
FROM `Users` as TM
INNER JOIN (
SELECT `UserID`, FIND_IN_SET(
Max(`Score`), (
select GROUP_CONCAT(
DISTINCT `Score`
order by `Score` DESC
)
From (
select MAX(`Score`) as `Score`
FROM `Users` as T0
GROUP BY `UserID`
) as T1
)
) as `rank`
FROM `Users` as T2
group by `UserID`
) as T3
ON TM.`UserID` = T3.`UserID`
-- If we need to filter or sort, we make it here :
WHERE TM.`UserID` = 192
ORDER BY TM.`Score`
答案 2 :(得分:0)
您可以计算得分较低的每位用户:
SELECT u.ID, u.UserID u.Score, 1 + COUNT(*) as Rank -- 1 + count every user with less score
FROM Users u
JOIN Users loser
ON loser.Score < u.score -- join with every user having less score
GROUP BY u.ID, u.UserID, u.Score
ORDER BY Rank