【发布时间】:2017-02-14 16:45:43
【问题描述】:
我有一张测试表:
category type quantities
a 1 100
a 2 150
b 2 45
b 3 68
b 1 72
c 2 90
c 3 39
假设只出现了 3 种类型。我的目标是选择各种类别和每种类型的数量。结果应该是:
类别 type1 type2 type3
a 100 150 0
b 72 45 68
c 0 90 39
我正在尝试联合,但我认为它是多余的而不是简短的:
select category, sum(type1)type1, sum(type2)type2 ,sum(type3) type3 from
(
select category, sum(quantities) type1, 0 type2, 0 type3 from test where type=1 group by category
union all
select category, 0 type1, sum(quantities) type2, 0 type3 from test where type=2 group by category
union all
select category, 0 type1, 0 type2, sum(quantities) type3 from test where type=3 group by category
) group by category;
我可以做些什么来缩短我的查询?感谢您的任何建议。
【问题讨论】: