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

Oracle SQL - Produce multiple different aggregations using analytic functions?

我有一个 table,我想按两个不同的列 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;

我会用分组集来做这个:

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()