繁体   English   中英

sql组的总和

[英]sql group by sum of all sums

我有一个查询(格式化为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

汇总五月份的发票。 结果类似于:

$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%)

有没有一种方法可以在查询中完成此操作?

只需使用解析函数:

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;

当功能完全满足您的需要时,最好使用这些功能。 在这种情况下,SQL Standard分析函数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, .....

to_charL元素用于货币符号; 您将货币符号定义为百分号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM