看看 Oracle 的分析函数。
例如:
with tab1 as (
select 'Dept 1' dept, 'Store 1' store, 'Region 1' region, 'ASmith' id, 101 salary, 1 overtime, 10 adjusted from dual union all
select 'Dept 1' dept, 'Store 1' store, 'Region 1' region, 'BSmith' id, 102 salary, 2 overtime, 10 adjusted from dual union all
select 'Dept 1' dept, 'Store 2' store, 'Region 1' region, 'CSmith' id, 104 salary, 4 overtime, 10 adjusted from dual union all
select 'Dept 1' dept, 'Store 2' store, 'Region 1' region, 'DSmith' id, 108 salary, 8 overtime, 10 adjusted from dual union all
select 'Dept 1' dept, 'Store 3' store, 'Region 1' region, 'DSmith' id, 108 salary, 8 overtime, 10 adjusted from dual union all
select 'Dept 2' dept, 'Store 1' store, 'Region 1' region, 'DSmith' id, 108 salary, 8 overtime, 10 adjusted from dual union all
select 'Dept 2' dept, 'Store 1' store, 'Region 1' region, 'ESmith' id, 116 salary, 16 overtime, 10 adjusted from dual union all
select 'Dept 2' dept, 'Store 2' store, 'Region 1' region, 'FSmith' id, 132 salary, 32 overtime, 10 adjusted from dual union all
select 'Dept 2' dept, 'Store 2' store, 'Region 1' region, 'ESmith' id, 116 salary, 16 overtime, 10 adjusted from dual union all
select 'Dept 2' dept, 'Store 3' store, 'Region 1' region, 'FSmith' id, 132 salary, 32 overtime, 10 adjusted from dual
)
select dept, store, region, sum(salary), sum(overtime), sum(adjusted)
from tab1
group by rollup(dept, store, region);
产生:
DEPT STORE REGION SUM(SALARY) SUM(OVERTIME) SUM(ADJUSTED)
------ ------- -------- ----------- ------------- -------------
Dept 1 Store 1 Region 1 203 3 20
Dept 1 Store 1 ** 203 3 20
Dept 1 Store 2 Region 1 212 12 20
Dept 1 Store 2 ** 212 12 20
Dept 1 Store 3 Region 1 108 8 10
Dept 1 Store 3 ** 108 8 10
Dept 1 ** ** 523 23 50
Dept 2 Store 1 Region 1 224 24 20
Dept 2 Store 1 ** 224 24 20
Dept 2 Store 2 Region 1 248 48 20
Dept 2 Store 2 ** 248 48 20
Dept 2 Store 3 Region 1 132 32 10
Dept 2 Store 3 ** 132 32 10
Dept 2 ** ** 604 104 50
** ** ** 1127 127 100
其中 ** 表示 NULL 值