# 计算一行占总和的百分比

13

``````Agent    |  Commission
---------|------------
Smith    |    100
Neo      |    200
Morpheus |    300
``````

``````Agent    |  Commission   |  % Commission
---------|---------------|---------------
Smith    |    100        |     17
Neo      |    200        |     33
Morpheus |    300        |     50
``````

Gaius

23

``````select
agent,
round(ratio_to_report(commission) over ()*100) "% Comm."
from
commissions;
``````

2011年

9

``````SELECT Agent, commission, 100* commission / (SUM(commission) OVER ()) "% Commission"
FROM commissions;
``````

``````create table commissions (Agent Varchar2(100), Commission Number(3));
insert into commissions values ('Smith',100);
insert into commissions values ('Neo',200);
insert into commissions values ('Morpheus',300);
``````

5

``````WITH TOTAL_COMMISSION AS
(SELECT SUM(COMMISSION) AS TOTAL FROM AGENTS)
SELECT A.AGENT_NAME, A.COMMISSION, ((A.COMMISSION/T.TOTAL)*100) AS "% COMMISSION"
FROM AGENTS A, TOTAL_COMMISSION T;
``````

Leigh Riffel

1
@Leigh〜由于手动方式需要两次通过，如何才能一次完成？我看不到计算机如何使％ofTotal成为一次神奇的单

@jcolebrand数据仅从数据库块读取一次。它可能正在对其内存结果进行多次传递，但这通常比两次读取数据库块要快。这些选项之间在内存和CPU之间需要权衡取舍，因此选择不一定总是很明确，但在这种情况下，我认为是这样。
Leigh Riffel

1
@Leigh ~~是的，进一步的考虑会使我相信它可以做的只是黑匣子抖动优化。无论如何，这是一个很不错的解决方案。谢谢：D
jcolebrand

0
``````  select
Agent, Commission,
(
ROUND(
(Commission *100) /
(
(SELECT SUM(Commission)
FROM commissions AS A)
)
)
) AS Porcentaje
from
commissions
``````