Oracle - 返回总和以及轮回的总和?

时间:2012-03-26 14:00:01

标签: oracle11g pivot

我想以下列格式返回结果集:

YEARMONTH Total ModelA ModelB ModelC
200101    0     0      0      0
200102    10    5      5      0
200103    8     2      2      4

其中,total是按年份分组的所有模型类型的小时数之和,而各个模型列是按年份分组的每个模型类型的小时数之和。我可以使用嵌套选择的以下查询获得正确的结果:

select distinct yearmonth,
    sum(a.hours) as Total,
    (select sum(b.hours) from model_hours b
        where model = 'ModelA' and a.yearmonth = b.yearmonth) as ModelA,
    (select sum(b.hours) from model_hours b
        where model = 'ModelB' and a.yearmonth = b.yearmonth) as ModelB,
    (select sum(b.hours) from model_hours b
        where model = 'ModelC' and a.yearmonth = b.yearmonth) as ModelC
from model_hours a
group by yearmonth
order by yearmonth

我很想尝试使用Oracle 11中的pivot功能来获得相同的结果,并且能够使用以下查询获得除总小时数之外的所有结果:

select * from (
    select yearmonth, hours, model
    from model_hours a
)
pivot
( 
    sum(hours)
    for model in ('ModelA', 'ModelB', 'ModelC')
)
order by yearmonth

返回此结果:

YEARMONTH  ModelA ModelB ModelC
200101     0      0      0
200102     5      5      0
200103     2      2      4

我无法弄清楚如何将所有模型的小时总和(按年)分组到此结果集中。可能吗?如果是这样,它是否可能比嵌套选择更有效?这个特殊的表现在有大约200K行。

1 个答案:

答案 0 :(得分:4)

在forums.oracle.com上,有几种类似的方法可以做到......最直接的语法似乎是:

select yearmonth,ModelA + ModelB + ModelC Total,ModelA,ModelB,ModelC from (
    select yearmonth, hours, model
    from model_hours a
)
pivot
( 
    sum(hours)
    for model in ('ModelA' as ModelA, 'ModelB' as ModelB, 'ModelC' as ModelC)
)
order by yearmonth

顺便说一下,使用标量子查询,透视查询比原始查询快约100倍!