代码之家  ›  专栏  ›  技术社区  ›  nicomp

Use ROLLUP with ORDER BY子句将总计行从下至上移动

  •  0
  • nicomp  · 技术社区  · 6 年前

    enter image description here

    这项工作:

    This works

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  3
  •   Gordon Linoff    6 年前

    您可以使用多个键来创建 order by :

    select coalesce(Genre, 'Grand Total'), sum(TotalUnits) as total_units_sold
    from album 
    group by Rollup (Genre) 
    order by (case when genre is null then 1 else 2 end) desc,
             genre;
    
        2
  •  0
  •   Avi    6 年前

    若您看到您是按列本身排序的,那个么当您使用汇总时,该值将保持为空。

    create table Album( Genre varchar(10), totalunits int)
    
    insert into Album values ('Pop', 100), 
    ('Pop', 200), 
    ('Pop', 300), 
    ('Rock', 500), 
    ('Rock', 1000), 
    ('Rock', 1500) 
    

    如果运行此查询,将获得此输出。

    select  Genre, sum(TotalUnits) [Total Units Sold]  from album 
    group by Rollup(Genre) 
    order by Genre
    

    Genre   Total Units Sold
    NULL    3600
    Pop     600
    Rock    3000
    

    select  Coalesce(Genre, 'Total') GenreNew, sum(TotalUnits) [Total Units Sold]  from album 
    group by Rollup(Genre) 
    order by Coalesce(Genre, 'Total')  
    

    select  Coalesce(Genre, 'Total') GenreNew, sum(TotalUnits) [Total Units Sold]  from 
    album 
    group by Rollup(Genre) 
    order by GenreNew 
    

    输出:

     GenreNew   Total Units Sold
     Pop        600
     Rock       3000
     Total      3600