【问题标题】:Order by a whole group整组订购
【发布时间】:2015-10-07 21:40:46
【问题描述】:

我有一张这样的桌子:

Brand | Type | Units
Sony | TV | 5
Toshiba | TV | 4
Sony | Radio | 1
Toshiba | Radio | 10

我想要这样:

Type | Brand | Units
Radio | Toshiba | 10
Radio | Sony | 1
TV | Sony | 5
TV | Toshiba | 4

也就是说,按类型品牌基于类型的数量(10+1 vs 5+4)然后按单位数量(10 vs 1 & 5与 4).

您认为实现这一目标的最佳方法是什么?

我尝试了以下方法,在每个组下添加了一个小计:

select Type, Brand, sum(Units) from mytable
group by Type, Brand, sum(Units) WITH ROLLUP

Type | Brand | sum(Units)
Radio | Toshiba | 10
Radio | Sony | 1
Radio | null | 11
TV | Sony | 5
TV | Toshiba | 4
TV | null | 9
null | null | 20

但我看不到按这些小计排序的方法。

【问题讨论】:

  • 加入派生表(带有别名的子查询)以获取小计。然后你可以通过他们订购。

标签: mysql sql rollup


【解决方案1】:

您可以将您的查询称为子查询并根据所需的列执行排序。

select type, brand, total
from (
select Type, Brand, sum(Units) as total
from mytable
group by Type, Brand, sum(Units) WITH ROLLUP) t
order by type, total desc

【讨论】:

    【解决方案2】:

    您想首先根据类型的总数按总数排序。在 MySQL 中,您可以使用显式聚合和join

    select tb.*
    from (select Type, Brand, sum(Units) as sumunits
          from mytable
          group by Type, Brand
         ) tb join
         (select Type, sum(Units) as sumunits
          from mytable
          group by Type
         ) t
         on tb.type = t.type
    order by t.sumunits desc, tb.sumunits desc;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-10
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      相关资源
      最近更新 更多