sql group by sum of sums

时间:2017-06-07 18:32:37

标签: sql oracle group-by

我有一个查询(格式化为Oracle):

select sum(inv.quantity * inv.price), spn.salesperson_name
from invoice inv
inner join salesperson spn on spn.spn_id = inv.spn_id
where inc.invoice_date between to_date('05/01/2017', 'MM/dd/YYYY') and to_date('05/31/2017', 'MM/dd/YYYY') 
group by spn.salesperson_name

添加5月份的发票。结果类似于:

$446,088.62     Bob
$443,439.29     Sally
$275,097.00     Tom
 $95,170.00     George
 $53,150.00     Jill

但是,我需要将每笔金额除以总和之和($ 1,312,944.91),结果是:

$446,088.62     34%  Bob
$443,439.29     34%  Sally
$275,097.00     21%  Tom
 $95,170.00      7%  George
 $53,150.00      4%  Jill

(百分比列的总和应为100%)

有没有办法在查询中完成此操作?

2 个答案:

答案 0 :(得分:2)

只需使用分析函数:

select spn.salesperson_name, sum(inv.quantity * inv.price), 
       sum(inv.quantity * inv.price)  / sum(sum(inv.quantity * inv.price)) over () as ratio 
from invoice inv inner join
     salesperson spn
     on spn.spn_id = inv.spn_id
where inc.invoice_date between date '2017-05-01' and date '2017-05-31'
group by spn.salesperson_name;

答案 1 :(得分:1)

当存在完全所需的功能时,最好使用这些功能。在这种情况下,SQL标准分析函数RATIO_TO_REPORT(至少在Oracle和SQL Server中实现)完全符合您的需要。 https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions124.htm

具体来说,select子句可以是:

select sum(inv.quantity * inv.price) AS TOTAL_REVENUE   --  use column aliases!
     , ratio_to_report(sum(inv.quantity * inv.price)) over () AS RATIO,
     , spn.salesperson_name
from   .......   (rest of your query goes here)

请注意,此解决方案(如“已接受的答案”)会将比率显示为小数,而不是百分比(而不是舍入)。如果您需要附加百分号,则需要转换为字符串...如果是这样,以下技巧(这是一个技巧!)将为您提供所需:

to_char( ratio_to_report(.....), 'fm99L', 'nls_currency = %' ) AS RATIO, .....

L中的to_char元素用于货币符号;您将货币符号定义为百分号。