带组的SQL Rank函数

时间:2019-03-10 12:35:43

标签: mysql sql group-by ranking

我想对一组用户的总统计数据进行排名,并为他们分配一个排名变量。 我使用this thread作为Rank变量。

这是我的查询atm:

SELECT @rank := @rank + 1 AS rank
     , SUM(stats.points) AS x 
  FROM 
     ( SELECT @rank := 0 ) r
     , groups 
  LEFT 
  JOIN user_group 
    ON groups.id = user_groups.clan 
  LEFT 
  JOIN stats 
    ON user_groups.user = stats.id 
 GROUP  
    BY groups.id 
 ORDER 
    BY x DESC

RANK | points 
--------------
  47 |    3400     
  1  |    2500     
  75 |    1200     

如您所见,按点排序效果很好,但是Rank变量似乎只是选择随机值。 谁能找到正确分配等级的方法?

1 个答案:

答案 0 :(得分:0)

使用子查询进行汇总和排序:

SELECT id, sum_points, @rank := @rank + 1 AS rank
FROM (SELECT g.id, SUM(s.points) AS sum_points
      FROM groups g LEFT JOIN
           user_group ug
           ON g.id = ug.clan LEFT JOIN
           stats s
           ON ug.user = s.id
      GROUP BY g.id
      ORDER BY sum_points DESC
     ) s CROSS JOIN
     (SELECT @rank := 0) params;

这在MySQL中已经存在了一段时间了-变量在聚合和排序方面无法很好地工作。

请注意,在MySQL 8+中,这更简单地写为:

SELECT g.id, SUM(s.points) AS sum_points,
       ROW_NUMBER() OVER (ORDER BY SUM(s.points) DESC) as rank
FROM groups g LEFT JOIN
     user_group ug
     ON g.id = ug.clan LEFT JOIN
     stats s
     ON ug.user = s.id
GROUP BY g.id