对计算的SUM值执行AVERAGE

时间:2013-03-27 14:04:27

标签: sql sql-server-2008 tsql aggregate-functions

我想获得计算出的SUM值的平均值,但是我收到一条错误,指出我“无法对包含聚合或子查询的表达式执行聚合函数。”

示例代码:

SELECT 
T.ReferenceNo,
Parts = ROUND(SUM(
    CASE
        WHEN T.AccountCode in ('value1', 'value2') THEN
            T.Amount
    END),2)
Labor = ROUND(SUM(
    CASE
        WHEN T.AccountCode in ('value1', 'value2') THEN
            T.Amount
    END),2)
FROM Transactions T

我想返回零件和人工的平均值,但是当我尝试将AVG函数包裹起来时,我得到了之前描述的错误。

我应该如何正确返回所需的平均值?

2 个答案:

答案 0 :(得分:0)

如果您只想要平均值而不是总和,只需将SUM替换为AVG

SELECT 
T.ReferenceNo,
Parts = ROUND(AVG(
    CASE
        WHEN T.AccountCode in ('value1', 'value2') THEN
            T.Amount
    END),2)
Labor = ROUND(AVG(
    CASE
        WHEN T.AccountCode in ('value1', 'value2') THEN
            T.Amount
    END),2)
FROM Transactions T

如果你想要两个值的平均值(两列),那么你可以使用:

(VALUE1 + VALUE2) / 2

答案 1 :(得分:0)

严格地说,PartsLabor可能为NULL,这会使简单平均计算混淆。我建议:

select t.ReferenceNo, t.Parts, t.Labor,
       (case when Parts is null then Labor
             when Labor is null then Parts
             else (Parts + Labor) / 2
        end) as AvgPartsLabor
from (SELECT T.ReferenceNo,
             Parts = ROUND(SUM(CASE WHEN T.AccountCode in ('value1', 'value2')
                                    THEN  T.Amount
                               END),2)
             Labor = ROUND(SUM(CASE WHEN T.AccountCode in ('value1', 'value2')
                                    THEN T.Amount
                               END),2)
      FROM Transactions T
      group by t.referenceNo
     ) t

如果要将NULL零件和人工值明确地视为0,请使用:

select t.ReferenceNo, t.Parts, t.Labor,
       (coalesce(Parts, 0) + coalesce(Labor, 0)) / 2
. . .