Average of multiple columns

前端 未结 5 1927
执念已碎
执念已碎 2020-12-01 14:13

I have a table called Request and the data looks like:

Req_ID    R1   R2   R3   R4   R5

R12673    2    5    3    7    10
R34721    3    5    2    1    8
R27         


        
5条回答
  •  醉酒成梦
    2020-12-01 14:39

    You don't mention if the columns are nullable. If they are and you want the same semantics that the AVG aggregate provides you can do (2008)

    SELECT *,
           (SELECT AVG(c)
            FROM   (VALUES(R1),
                          (R2),
                          (R3),
                          (R4),
                          (R5)) T (c)) AS [Average]
    FROM   Request  
    

    The 2005 version is a bit more tedious

    SELECT *,
           (SELECT AVG(c)
            FROM   (SELECT R1
                    UNION ALL
                    SELECT R2
                    UNION ALL
                    SELECT R3
                    UNION ALL
                    SELECT R4
                    UNION ALL
                    SELECT R5) T (c)) AS [Average]
    FROM   Request
    

提交回复
热议问题