对结果集分组

时间:2019-12-18 12:02:18

标签: mysql sql ranking

我希望有一列显示此结果集的排名(最高金额为#1)。可以以某种方式做到这一点吗? 这是产生this result的查询:

    For Each cell In pswarray
        If cell = Merkmal Then
            Password = ("C" & zeile)
            zeile = zeile + 1
        End If '<<---- this was missing.
    Next cell

1 个答案:

答案 0 :(得分:0)

我预感您实际上使用过MariaDB。
(基于您在已删除答案中的评论)

然后,您可以尝试将SUM上的DENSE_RANK添加到SELECT

DENSE_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) rnk
from test
group by col1
order by rnk
col1 | tot | rnk
---: | --: | --:
   2 |  10 |   1
   1 |   6 |   2
   3 |   6 |   2
   4 |   3 |   3

db <>提琴here

在MySql 5.7中,可以通过变量进行仿真

例如:

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
) q2
order by rnk;
col1 | total | rnk
---: | ----: | :--
   2 |    10 | 1  
   1 |     6 | 2  
   3 |     6 | 2  
   4 |     3 | 3  

db <>提琴here