由整个团体订购

时间:2015-10-07 21:40:47

标签: 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

也就是说,按照类型品牌为基础,按类型计数(10 + 1对5 + 4),然后按单位数量(10对1& 4)进行排序。 5 vs 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

但我认为没办法按小计排序。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您希望根据其总数首先按类型的总数进行排序。在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;