[英]Find avg of each row from the grand total
我有以下幾欄的銷售表sale
sale_id | 部門| gross_amount
我需要從總銷售額中找到每個部門的平均銷售額
例如:- 表格
sale_id Department gross_amount
1 A 10
2 B 30
3 A 25
4 c 5
Desired output
Department Gross_amount avg
A 35 50 --(35/70)*100
B 30 42.86 --(30/70)*100
C 5 7.14 --(5/70) *100
即是dept_avg =(dept_total /總數)* 100例如:-A的dept_total總數= 35總數= A + B + C = 35 + 30 + 5 = 70
我最多可以找到Gross_amount
select Department ,sum(si.GrossPrice) gross_amt
from Sale si
group by Department
order by Department
為了獲得平均值,我嘗試按照
select Department ,sum(si.GrossPrice) gross_amt,
AVG(sum(si.GrossPrice)) avg
from Sale si
group by Department
order by Department
這給我一個錯誤
無法對包含聚合或子查詢的表達式執行聚合功能。
另外,我不確定我可以通過上述查詢獲得預期的平均值。 我怎么能達到同樣的目的。
將分組的總和除以總和:
SELECT Department ,
[Gross_amount] = SUM(gross_amount),
[avg] = ROUND(CAST(SUM(gross_amount) AS DECIMAL(10,2))/
CAST((SELECT SUM(gross_amount) FROM tab) AS DECIMAL(10,2)) * 100
,2)
FROM tab
GROUP BY Department
ORDER BY Department
如果您希望每個部門在總部門中所占的比例,我建議使用窗口函數:
SELECT Department, SUM(gross_amount) as gross_amount
SUM(gross_amount)*100.0 / SUM(SUM(gross_amount)) over () as propotion
FROM tab
GROUP BY Department
ORDER BY Department;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.