简体   繁体   English

从总计中查找每一行的平均值

[英]Find avg of each row from the grand total

I have a sales table sale with following columns 我有以下几栏的销售表sale

sale_id | sale_id | Department | 部门| gross_amount gross_amount

I need to find the avg of sales in each department from the total sale 我需要从总销售额中找到每个部门的平均销售额

eg:- Table 例如:- 表格

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

ie is dept_avg = (dept_total / total) *100 eg:- dept_total of A = 35 total = A+B+C = 35+30+5 =70 即是dept_avg =(dept_total /总数)* 100例如:-A的dept_total总数= 35总数= A + B + C = 35 + 30 + 5 = 70

I am able to find up to Gross_amount 我最多可以找到Gross_amount

select Department ,sum(si.GrossPrice)  gross_amt
from Sale si
group by Department 
order by Department

For getting avg I tried follow 为了获得平均值,我尝试按照

 select Department ,sum(si.GrossPrice) gross_amt,
    AVG(sum(si.GrossPrice)) avg
    from Sale si
    group by Department 
    order by Department

It is giving me an error 这给我一个错误

Cannot perform an aggregate function on an expression containing an aggregate or a subquery. 无法对包含聚合或子查询的表达式执行聚合功能。

Also I am not sure i can get my expected avergage with the above query. 另外,我不确定我可以通过上述查询获得预期的平均值。 How can I achieve the same. 我怎么能达到同样的目的。

Divide grouped sum by total sum: 将分组的总和除以总和:

SqlFiddleDemo SqlFiddleDemo

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

If you want the proportion of the total for each department out of the overall total, I would suggest using window functions: 如果您希望每个部门在总部门中所占的比例,我建议使用窗口函数:

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.

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