具有不同数据的多个列的平均值

时间:2015-02-18 10:35:46

标签: sql sql-server sql-server-2012

我有10个十进制列,我想在我的表中添加一个计算列,其中包含这些列的平均值。复杂的是,并非每个记录都填充了所有10列。有些记录有4个有8个和有些人有10人。

e.g。

ID D1 D2 D3 D4 D5 D6 D7 D8 D9 D10
1  12 19 13 14
2  32 53 34 54 65 34 12 09
3  41 54 33 61 71 12 09 08 08 12

如何获得ID1 = 14.5,ID2 = 36.625等的平均值

我不能做D1 + D2 + D3 ...... / 10,因为10不总是10

理想只是做AVG(D1:D10),但显然世界并不理想!

3 个答案:

答案 0 :(得分:3)

您无法使用AVG聚合功能(因为它适用于行),但您可以使用以下查询计算平均值:

SELECT 
    (ISNULL(D1,0) + ISNULL(D2,0) + 
    ISNULL(D3,0) + ISNULL(D4,0) + ISNULL(D5,0) + 
    ISNULL(D6,0) + ISNULL(D7,0) + ISNULL(D8,0) + 
    ISNULL(D9,0) + ISNULL(D10,0)) /
    CASE 
    WHEN 
        D1 IS NOT NULL 
        OR D2 IS NOT NULL
        OR D3 IS NOT NULL
        OR D4 IS NOT NULL
        OR D5 IS NOT NULL
        OR D6 IS NOT NULL
        OR D7 IS NOT NULL
        OR D8 IS NOT NULL
        OR D9 IS NOT NULL
        OR D10 IS NOT NULL
    THEN
        (
        CASE
            WHEN D1 IS NOT NULL THEN 1 ELSE 0
        END +
        CASE
            WHEN D2 IS NOT NULL THEN 1 ELSE 0
        END +
        CASE
            WHEN D3 IS NOT NULL THEN 1 ELSE 0
        END +
        CASE
            WHEN D4 IS NOT NULL THEN 1 ELSE 0
        END +
        CASE
            WHEN D5 IS NOT NULL THEN 1 ELSE 0
        END +
        CASE
            WHEN D6 IS NOT NULL THEN 1 ELSE 0
        END +
        CASE
            WHEN D7 IS NOT NULL THEN 1 ELSE 0
        END +
        CASE
            WHEN D8 IS NOT NULL THEN 1 ELSE 0
        END +
        CASE
            WHEN D9 IS NOT NULL THEN 1 ELSE 0
        END +
        CASE
            WHEN D10 IS NOT NULL THEN 1 ELSE 0
        END
        )
   ELSE 1
   END
FROM yourtable

答案 1 :(得分:1)

每个ID的AVG:

select id, avg(d) from
(
select id, id1 as d from tablename
union all
select id, id2 as d from tablename
union all
select id, id3 as d from tablename
union all
select id, id4 as d from tablename
union all
select id, id5 as d from tablename
union all
select id, id6 as d from tablename
union all
select id, id7 as d from tablename
union all
select id, id8 as d from tablename
union all
select id, id9 as d from tablename
union all
select id, id10 as d from tablename)
group by id

答案 2 :(得分:1)

Values表值构造函数用于unpivot数据,然后按average查找ID。试试这个

select id,avg(data) from Yourtable 
cross apply 
(values(D1), (D2), (D3), (D4), (D5), (D6) ,(D7), (D8), (D9) ,(D10)) cs (data)
group by id

或者如果你想要的小数值,那么使用它。

select id,sum(data)/sum(case when data is not null then 1.0 else 0 end) from Yourtable 
cross apply 
(values(D1), (D2), (D3), (D4), (D5), (D6) ,(D7), (D8), (D9) ,(D10)) cs (data)
group by id