1
 SELECT a.userid, u.name, u.profilePic , 
   SUM(activity_weight) AS totalPoints, 
  (SELECT @rank:=1 +1) AS rank
 FROM activity_entries a 
 INNER JOIN users1 u ON u.id = a.userid 
 WHERE competitionId = '5216078af3730' 
 GROUP BY a.userid 
 ORDER BY totalPoints DESC

所以我有这个运行良好的 SQL 查询,我根据需要返回totalPoints,但我也希望获得每个结果的排名/行位置。

目前,上面的查询为每一行返回排名 2,显然没有正确递增。

希望得到一些帮助/建议!

Ĵ

4

1 回答 1

2

尝试这个 :

(SELECT @rank:=@rank +1)

对于您刚刚添加的每一行,1 + 1 始终为 2。

编辑:

您需要初始化变量:

SET @rank=0;

您需要在使用相同的连接之前执行此查询。

SELECT
    tmp.userid,
    tmp.name,
    tmp.profilePic,
    tmp.totalPoints,
    (SELECT @rank:=@rank +1) AS rank
FROM (
    SELECT 
        a.userid, 
        u.name, 
        u.profilePic , 
        SUM(activity_weight) AS totalPoints
    FROM 
        activity_entries a 
    INNER JOIN users1 u 
        ON u.id = a.userid 
    WHERE 
        competitionId = '5216078af3730' 
    GROUP BY 
        a.userid 
    ORDER BY 
        totalPoints DESC
) as tmp
于 2013-09-16T12:33:32.407 回答