Oracle SQL - 使用分析函数生成多个不同的聚合?
Posted
技术标签:
【中文标题】Oracle SQL - 使用分析函数生成多个不同的聚合?【英文标题】:Oracle SQL - Produce multiple different aggregations using analytic functions? 【发布时间】:2015-08-13 01:16:37 【问题描述】:我有一个表,我想按两个不同的列聚合,prop1
和 prop2
。
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】:我会通过分组来做到这一点:
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_ID
或GROUP_ID()
,但我认为使用COALESCE()
更容易理解逻辑。
【讨论】:
以上是关于Oracle SQL - 使用分析函数生成多个不同的聚合?的主要内容,如果未能解决你的问题,请参考以下文章
如何将 SQL 结果生成到 Excel 工作表 (Oracle)