所以我有一个MySQL数据库
CREATE TABLE `all_time_earners` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`image` varchar(250) NOT NULL,
`username` varchar(250) NOT NULL,
`earnings` int(11) NOT NULL,
`rank` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
这就是我的桌子的样子
id username earnings rank
====================================================
1, ken, 100, 0
2, dave, 50, 0
3, bob, 300, 0
4, ken, 150, 0
5, ken, 200, 0
我正在尝试使用GROUP BY用户名,但不会为使用的用户显示多个条目
"SELECT * FROM all_time_earners GROUP BY username ORDER BY earnings DESC;"
问题在于它不能汇总收益
请问有人对我做错了吗?
如何对这些用户进行排名,例如:收入最高的用户排名1,其次是排名2,等等
答案 0 :(得分:2)
我相信使用Mysql 5.7可以实现所需的目标:
SELECT username,
SUM(earnings) AS totalEarnings
FROM all_time_earners ate
GROUP BY username
ORDER BY totalEarnings DESC;
如果要添加等级号:
SET @row_number = 0;
SELECT te.*,
@row_number := @row_number + 1 AS rank
FROM (
SELECT username,
SUM(earnings) AS totalEarnings
FROM all_time_earners ate
GROUP BY username
ORDER BY totalEarnings DESC
) te
中查看