Oracle SQL - 使用分析函数生成多个不同的聚合?

时间:2015-08-13 01:16:37

标签: sql oracle query-optimization window-functions

我有一个表格,我希望通过两个不同的列prop1prop2进行汇总。

 id | prop1 | prop2 | val
--------------------------
 1  | A     | B     | 10
 2  | A     | A     | 15
 3  | B     | B     | 20
 4  | B     | A     | 30

所需的输出是:

 prop_name | prop_val | sum_val
--------------------------------
 prop1     | A        | 25
 prop1     | B        | 50
 prop2     | A        | 45
 prop2     | B        | 30

我知道我可以使用联合(见下文)来做到这一点,但使用分析函数有更好的方法吗?

with 
  test_data as (
      select 1 as id, 'A' as prop1, 'B' as prop2, 10 as val from dual union all
      select 2 as id, 'A' as prop1, 'A' as prop2, 15 as val from dual union all
      select 3 as id, 'B' as prop1, 'B' as prop2, 20 as val from dual union all
      select 4 as id, 'B' as prop1, 'A' as prop2, 30 as val from dual
  )
select
   'prop1' as prop_name
  , prop1 as prop_val
  , sum(val)  as sum_val
from test_data
group by 'prop1', prop1

union all

select
  'prop2' as prop_name
  , prop2 as prop_val
  , sum(val)  as sum_val
from test_data
group by 'prop2', prop2;

1 个答案:

答案 0 :(得分:0)

我会用分组集来做到这一点:

select prop1, prop2, sum(val)
from test_data
group by grouping sets ((prop1), (prop2))

Here就是你的榜样。

获得准确的输出需要更多的工作。

select (case when prop1 is null then 'prop2' else 'prop1' end) as prop_name,
       coalesce(prop1, prop2) as prop,
       sum(value)
from test_data
group by grouping sets ((prop1), (prop2));

这假定前两列不包含NULL值。表达逻辑的更好方法是使用GROUPING_IDGROUP_ID(),但我认为COALESCE()更容易遵循逻辑。