嘗試使用OLAP函數rollup
和grouping
這樣的:
select
nvl(subregion, region) region, sum("sum")
from t
group by region, rollup(subregion)
having case when count(*) = 1 then 0 else 1 end = grouping(subregion);
在上文中,
having case when count(*) = 1 then 0 else 1 end = grouping(subregion);
上述不包括的rolluped行是否有用於該區域只有一行,以便有沒有重複。
另外,請避免在標識符中使用保留關鍵字,例如sum或count。
演示:
SQL> with t(REGION ,SUBREGION ,s) as (
2 select 'CORP' , 'CORP1' , 5 from dual union all
3 select 'CORP' , 'CORP2' , 10 from dual union all
4 select 'CORP' , 'CORP3' , 5 from dual union all
5 select 'SB' ,'SB1' ,10 from dual union all
6 select 'SB' ,'SB2' ,10 from dual union all
7 select 'MID' , null , 10 from dual union all
8 select 'LARGE' , null , 20 from dual
9 )
10 select
11 nvl(subregion, region) region, sum(s)
12 from t
13 group by region, rollup(subregion)
14 having case when count(*) = 1 then 0 else 1 end = grouping(subregion);
REGIO SUM(S)
----- ----------
SB1 10
SB2 10
SB 20
MID 10
CORP1 5
CORP2 10
CORP3 5
CORP 20
LARGE 20
9 rows selected.
SQL>
你有什麼嘗試?你是如何產生第一份報告的(因爲第二份報告只是一個小小的改動)。 – AndySavage