我想有一列显示此结果集的排名(最高金额为#1)。能以某种方式做到这一点吗?这是产生this result的查询:SELECT user_names.user_name,city.city,state.state,SUM(events_full.amount) AS totalFROM user_names,city,state,events_fullWHERE user_names.user_id=events_full.user_idAND city.city_id=events_full.city_idAND state.state_id=events_full.state_idAND events_full.season_id=13AND amount > 0Group By user_names.user_name 最佳答案 我预感您实际上使用了MariaDB。(根据您在已删除答案中的评论)然后,您可以尝试在SUM上的SELECT上添加DENSE_RANKDENSE_RANK() OVER (ORDER BY SUM(events_full.amount) DESC) AS Ranking一个简单的例子:create table test( col1 int, col2 int);insert into test values(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(2,4),(3,1),(3,5),(4,1),(4,2);select col1, sum(col2) tot, dense_rank() over (order by sum(col2) desc) rnkfrom testgroup by col1order by rnkcol1 | tot | rnk---: | --: | --: 2 | 10 | 1 1 | 6 | 2 3 | 6 | 2 4 | 3 | 3db<>fiddle hereIn MySql 5.7 it can be emulated via variablesFor example:select *from( select col1, total , case when total = @prev_tot and @prev_tot := total then @rnk when @prev_tot := total then @rnk := @rnk + 1 end as rnk from ( select col1 , sum(col2) as total from test group by col1 order by total desc ) q1 cross join (select @rnk:=0, @prev_tot:=0) v) q2order by rnk;col1 |总计nk---: ----:| :-   2 | 10 | 1   1 | 6 | 2   3 | 6 | 2   4 | 3 | 3db 小提琴here关于mysql - 对结果分组排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59391626/
10-12 18:34