[英]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_char
的L
元素用於貨幣符號; 您將貨幣符號定義為百分號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.