3

我有一个关于 MySQL 数据库的查询,我得到这个结果:

> Rank  Gold    Silver  Bronze  Total 
> 1     76      78      77      231 
> 2     4       5       6       15 
> 3     4       1       1       6
> 4     3       0       0       3 
> 5     2       1       1       4 
> 5     2       1       1       4
> 6     2       0       0       2
> 7     1       1       1       3
> 8     1       1       0       2
> 9     1       0       2       3
> 9     1       0       2       3
> 9     1       0       2       3
> 10    0       1       0       1

我从中获得此结果的查询如下(我隐藏了主查询,以免编写太多代码):

select
    CASE
        WHEN (@Gold=T.Gold and @Silver=T.Silver and @Bronze=T.Bronze) THEN @rownum ELSE @rownum:=@rownum+1 end as Rank,        

        (@Gold:=T.Gold) Gold,
        (@Silver:=T.Silver) Silver,
        (@Bronze:=T.Bronze) Bronze,
        T.Total

from

(MAIN_QUERY) T,

(SELECT @rownum:=0) r, 
    (SELECT @Gold:=0) g,
    (SELECT @Silver:=0) s,
    (SELECT @Bronze:=0) b

   order by Gold desc, Silver DESC, Bronze DESC

但是,而不是上面的结果,我想调整 Rank 列(和我的查询),根据重复的先前行增加它,即:

> Rank  Gold    Silver  Bronze  Total 
    > 1     76      78      77      231 
    > 2     4       5       6       15 
    > 3     4       1       1       6
    > 4     3       0       0       3 
    > 5     2       1       1       4 
    > 5     2       1       1       4
    > 7     2       0       0       2
    > 8     1       1       1       3
    > 9     1       1       0       2
    > 10    1       0       2       3
    > 10    1       0       2       3
    > 10    1       0       2       3
    > 13    0       1       0       1

等等。你能帮我得到这个结果吗?

4

1 回答 1

2

也许另一个变量可以做到这一点:

SELECT @rownum := @rownum + 1, 
       CASE 
         WHEN ( @gold = T.gold 
                AND @silver = T.silver 
                AND @bronze = T.bronze ) THEN @rank := @rank 
         ELSE @rank := @rownum 
       END                     AS Rank, 
       ( @gold := T.gold )     Gold, 
       ( @silver := T.silver ) Silver, 
       ( @bronze := T.bronze ) Bronze, 
       T.total 
FROM   (MAIN_QUERY) T 
       CROSS JOIN (SELECT @rownum := 0, 
                          @gold := 0, 
                          @silver := 0, 
                          @bronze := 0, 
                          @rank := 0) v 
ORDER  BY gold DESC, 
          silver DESC, 
          bronze DESC 

Here is a demo

注意:如果您的数据的所有列都是 0,这将不起作用。

于 2016-08-04T05:19:52.113 回答