您的位置:首页 > 数据库 > Oracle

oracle分析函数系列之ratio_to_report:计算占总数百分比

2012-06-19 11:39 537 查看
数据库如何用Oracle RATIO_TO_REPORT计算总数百分比

除报告详细数据外,许多报告中还包括每行总数的百分比。例如,每名客户的订单相对于总订单的百分比,或每位销售代表的销售额相对于总销售额的百分比。

传统上,Oracle计算百分比的方法是在总计报告的子查询中使用SUM函数总计报告,然后把那个结果放到细节表中相除来计算百分比。你还可以用一个子查询作为SELECT语句表达式:

RATIO_TO_REPORT解析函数使得这种类型的查询更容易编码。Oracle 8i中引入了这个函数,它的格式如下:

RATIO_TO_REPORT (expr) OVER (query_partition_clause)

列表A说明一个简单的例子。对163号销售代表来说,每位客户的销售额占这名销售代表的总销售额的百分比是多少呢?在这种情况下,查询分区子句(partition clause)为空,因此得到的结果是对返回的所有行计算得出。

列表B增加了一个查询分区子句,进一步按客户细分报告。PARTITION BY customer_id子句重新安排每位客户的总数,进而说明每名客户的哪次订单最为关键。你可以查看客户102的情况,他的两个订单相对平衡;

但客户103的一个订单占这名客户总订单额的很大一部分。

Listing A

SELECT

sales_rep_id, customer_id, order_total,

ratio_to_report(order_total) OVER () pct_total

FROM

orders

WHERE

sales_rep_id = 163

ORDER BY

sales_rep_id, customer_id, order_id

/

SQL> @ratioreport_a

SALES_REP_ID CUSTOMER_ID ORDER_TOTAL PCT_TOTAL

------------ ----------- ----------- ----------

163 102 5610.6 .043747539

163 102 10523 .082051002

163 103 78 .00060819

163 103 13550 .105653433

163 105 1926.6 .015022281

163 106 5546.6 .043248512

163 117 3878.4 .030241054

163 147 1500.8 .01170219

163 149 9055 .070604564

163 156 68501 .53412294

163 157 7110.3 .055441152

163 160 969.2 .007557144

12 rows selected.

===========================================================

Listing B

col order_total format 999,999.00

col pct_total format 999.00

SELECT

sales_rep_id,

customer_id,

order_total,

ROUND(100*ratio_to_report(order_total)

OVER (PARTITION BY customer_id),2) pct_total

FROM

orders

WHERE

sales_rep_id = 163

ORDER BY

sales_rep_id, customer_id, order_id/

SQL> @ratioreport_b

SALES_REP_ID CUSTOMER_ID ORDER_TOTAL PCT_TOTAL

------------ ----------- ----------- ---------

163 102 5,610.60 34.78

163 102 10,523.00 65.22

163 103 78.00 .57

163 103 13,550.00 99.43

163 105 1,926.60 100.00

163 106 5,546.60 100.00

163 117 3,878.40 100.00

163 147 1,500.80 100.00

163 149 9,055.00 100.00

163 156 68,501.00 100.00

163 157 7,110.30 100.00

163 160 969.20 100.00

12 rows selected.

===============================================================

SELECT last_name, salary, RATIO_TO_REPORT(salary) OVER () AS rr

FROM employees

WHERE job_id = 'PU_CLERK';

LAST_NAME SALARY RR

------------------------- ---------- ----------

Khoo 3100 .223021583

Baida 2900 .208633094

Tobias 2800 .201438849

Himuro 2600 .18705036

Colmenares 2500 .179856115
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: