SQL 带组的排名函数
SQL Rank Function with Group
我想对一组用户的总统计数据进行排名,并为他们分配一个排名变量。
我使用 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 变量似乎只是选择随机值。
谁能找到正确分配等级的方法?
使用子查询进行聚合和排序:
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
我想对一组用户的总统计数据进行排名,并为他们分配一个排名变量。 我使用 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 变量似乎只是选择随机值。 谁能找到正确分配等级的方法?
使用子查询进行聚合和排序:
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