0

我在 SQL Server 中有一个存储过程,它返回一些列的平均值,如下所示:

ALTER PROCEDURE [dbo].[Financial] 
AS
BEGIN
    SELECT 
        avg([aa ]) as 'aaa',
        avg([bb]) as 'bbb',
        avg([cc ]) as 'ccc',
        avg([dd]) as 'ddd',
        avg([ee]) as 'eee',
        avg([ ff]) as 'fff'
    FROM [FIN]
END

现在我的问题是我想得到这个过程结果的平均值,我的意思是这个当前过程给了我一行它包含某列的平均值。现在我想要这一行的平均值!我能做些什么?

让我解释一下上述过程的结果可能是:

4,7,8,9,6

接下来我想要平均值

4,7,8,9,6 
4

1 回答 1

1

处理 NULL 值是一件很痛苦的事情。如果列中的所有值都可以为 NULL,则以下将计算平均值:

SELECT aaa, bbb, ccc, ddd, eee, fff,
    ((coalesce(aaa, 0) + coalesce(bbb, 0) + coalesce(ccc, 0) + coalesce(ddd, 0) +
      coalesce(eee, 0) + coalesce(fff, 0)) /
     ((case when aaa is null then 0.0 else 1.0 end) +
      (case when bbb is null then 0.0 else 1.0 end) +
      (case when ccc is null then 0.0 else 1.0 end) +
      (case when ddd is null then 0.0 else 1.0 end) +
      (case when eee is null then 0.0 else 1.0 end) +
      (case when fff is null then 0.0 else 1.0 end)
     )
    ) AS Average
FROM (
    SELECT 
        avg([aa ]) as 'aaa',
        avg([bb]) as 'bbb',
        avg([cc ]) as 'ccc',
        avg([dd]) as 'ddd',
        avg([ee]) as 'eee',
        avg([ ff]) as 'fff'
    FROM [FIN]
) AS Averages
于 2012-10-01T18:31:32.200 回答