Mysql 集体订货

Mysql 集体订货,mysql,sql,rollup,Mysql,Sql,Rollup,我有一张这样的桌子: 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 我希望它是这样的: Brand | Type | Units Sony | TV | 5 Toshiba | TV

我有一张这样的桌子:

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
我希望它是这样的:

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对5+4)然后根据单位计数(10对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

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

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

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

您希望首先根据类型的总计对其进行排序。在MySQL中,您可以通过显式聚合和
连接来实现这一点:

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;
连接到派生表(带别名的子查询)以获取小计。然后你可以按他们点菜。