从总计中找到每行的平均值

时间:2015-09-07 19:03:14

标签: sql sql-server-2008 average

我有一个销售表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 / total)* 100 例如: - dept_total A = 35      total = 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

它给了我一个错误

  

无法对包含的表达式执行聚合函数   聚合或子查询。

此外,我不确定我是否可以通过上述查询得到我预期的优惠。我怎样才能实现同样的目标。

2 个答案:

答案 0 :(得分:2)

将总和除以总和:

<强> 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

答案 1 :(得分:0)

如果你想要每个部门的总数占总数的比例,我建议使用窗口函数:

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;