Oracle SQL ratio_to_report函数、占比统计
2017-07-03 14:23
274 查看
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
源表数据
--需求1 按区域统计销售额占比
--需求2 按月份分组,计算每个区域销售额占当月销售总额比重
数据库版本
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
相关文章推荐
- 【SQL】分组再聚合&ratio_to_report函数
- oracle ratio_to_report 占比函数
- oracle 求男女比例 sql 函数ratio_to_report
- ORACLE HANDBOOK系列之六:ODP.NET与复杂的PL/SQL数据类型(Using ODP.NET To Deal With Complex PLSQL Data Types)
- Related to Oracle SQL 关于选择前N行数据的SQL语句
- 在Oracle的SQL*PLUS中启用AutoTrace查看SQL执行计划和统计信息
- ORACLE 统计正负个数sql
- oracle sql to_char使用注意
- Oracle Bug: WARNING:Could not lower the asynch I/O limit to 224 for SQL direct I/O. It is set to -1
- Related to Oracle SQL 由Not in 引起取不到数据的错误
- Related to Oracle SQL 关于优化,SQL语句的共享[笔记]
- Related to Oracle SQL 关于树形数据的遍历
- oracle pl/sql to_date日期类型格式转换
- How to setup linked servers for SQL Server and Oracle 64 bit client
- How to change the language of oracle sqlplus from chinese to english in windows(如何将oracle sql plus中的中文变成英文版)
- Related to Oracle SQL 关于Oracle大数据量处理与表分区
- oracle分组统计sql
- 简单骗过DataContext,统计Linq to SQL执行查询的次数
- Reading and Writing BLOB Data to MS SQL or Oracle Database
- Related to Oracle SQL 关于检验字符串是否为数字类型的方法