Oracle分析函數 ratio_to_report,可以非常方便實現某列統計值佔整個分組的比例。如統計某個區域銷量佔總銷量的比重,某個月份銷量佔總銷量的比重等。
數據庫版本
SQL> select * from v$version;
BANNER
--------------------------------------------------------------------------------
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
PL/SQL Release 11.2.0.4.0 - Production
CORE 11.2.0.4.0 Production
TNS for Linux: Version 11.2.0.4.0 - Production
NLSRTL Version 11.2.0.4.0 - Production
源表數據
SQL> select * from t;
MONTH_ID AREA SALE
--------- ---- ----
201701 華北 100
201701 華南 40
201701 華東 40
201701 西北 20
201702 華北 100
201702 華南 40
201702 華東 40
201702 西北 20
--需求1 按區域統計銷售額佔比
--常規實現,用分析函數sum() over() 計算出分組的合計值
SQL> select t.area,
2 sum(sale) sale_sum,
3 sum(sum(sale)) over() sale_total,
4 sum(sale) / sum(sum(sale)) over() sale_ratio
5 from t
6 group by t.area;
AREA SALE_SUM SALE_TOTAL SALE_RATIO
---------- ---------- ---------- ----------
華北 200 400 0.5
華南 80 400 0.2
華東 80 400 0.2
西北 40 400 0.1
--ratio_to_report 分析函數實現
SQL> select t.area,
2 sum(sale) sale_sum,
3 ratio_to_report(sum(sale)) over() sale_ratio
4 from t
5 group by t.area;
AREA SALE_SUM SALE_RATIO
---------- ---------- ----------
華北 200 0.5
華南 80 0.2
華東 80 0.2
西北 40 0.1
--需求2 按月份分組,計算每個區域銷售額佔當月銷售總額比重
SQL> select t.month_id,
2 t.area,
3 sale,
4 ratio_to_report(sale) over(partition by t.month_id) sale_ratio
5 from t;
MONTH_ID AREA SALE SALE_RATIO
------ ------ -------- -------
201701 華北 100 0.5
201701 華東 40 0.2
201701 華南 40 0.2
201701 西北 20 0.1
201702 華北 100 0.5
201702 華東 40 0.2
201702 華南 40 0.2
201702 西北 20 0.1