【问题标题】:Make a grouping and transforming query Oracle进行分组和转换查询 Oracle
【发布时间】: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;

我可以做些什么来缩短我的查询?感谢您的任何建议。

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    那是简单的条件聚合:

    select 
      category,
      nvl(sum(case when type = 1 then quantities end), 0) as type1,
      nvl(sum(case when type = 2 then quantities end), 0) as type2,
      nvl(sum(case when type = 3 then quantities end), 0) as type3
    from mytable
    group by category
    order by category;
    

    【讨论】:

    • 为什么我把它弄得太复杂了?如此清晰和简单。谢谢!
    【解决方案2】:

    【讨论】:

    • 感谢您提供有用的文档。
    猜你喜欢
    • 2015-04-14
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 2018-11-01
    • 2016-04-10
    • 2013-07-10
    相关资源
    最近更新 更多