[英]sql group by sum of all sums
I have a query (formatted for Oracle): 我有一个查询(格式化为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
To add up invoices for the month of May. 汇总五月份的发票。 The result is similar to: 结果类似于:
$446,088.62 Bob
$443,439.29 Sally
$275,097.00 Tom
$95,170.00 George
$53,150.00 Jill
But, I need to divide each sum to the sum of the sums ($1,312,944.91), so that the result is: 但是,我需要将每个总和除以总和($ 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
(The sum of the percentage column should be 100%) (百分比列的总和应为100%)
Is there a way to accomplish this in the query? 有没有一种方法可以在查询中完成此操作?
Just use analytic functions: 只需使用解析函数:
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;
When functions exist that do exactly what you need, it is best to use those functions. 当功能完全满足您的需要时,最好使用这些功能。 In this case, the SQL Standard analytic function RATIO_TO_REPORT
(which is implemented at least in Oracle and SQL Server) does exactly what you need. 在这种情况下,SQL Standard分析函数RATIO_TO_REPORT
(至少在Oracle和SQL Server中实现)可以完全满足您的需求。 https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions124.htm https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions124.htm
Specifically, the select
clause could be: 具体来说, 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)
Note that this solution, like the Accepted Answer, will show the ratio as a decimal, not as a percentage (and not rounded). 请注意,此解决方案与“接受的答案”一样,将比率显示为小数而不是百分比(并且不四舍五入)。 If you need to attach a percentage sign, you will need to convert to string... and if so, the following trick (it is a trick!) will give you what you need: 如果需要附加百分号,则需要将其转换为字符串...,如果是这样,以下技巧(这是一个技巧!)将为您提供所需的信息:
to_char( ratio_to_report(.....), 'fm99L', 'nls_currency = %' ) AS RATIO, .....
The L
element in to_char
is for currency symbol; to_char
的L
元素用于货币符号; you define the currency symbol to be the percent sign. 您将货币符号定义为百分号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.