开发者

how do I select AVG of multiple columns on a single row

How can I select average of multiple columns?

Suppose I have some data like:

X   Y    Z
-------------
6   3    3
5   5    NULL
4   5    6
11  7    8

I want to get something like

AVG
-------------
4
5
5
8.66666667

I tried select avg(x, y, z) from table

But it doesn't work.

开发者_如何学Go

Any ideas on a query to do that?


Try

 Select     (Coalesce(x,0) + Coalesce(y,0) + Coalesce(z,0)) /
       (Coalesce(x/x, 0) + Coalesce(y/y, 0) + Coalesce(z/z, 0))

or

 Select (Coalesce(x,0) + Coalesce(y,0) + Coalesce(z,0)) /
         (Case When x Is Null 0 Else 1 End +
          Case When y Is Null 0 Else 1 End +
          Case When z Is Null 0 Else 1 End)


You add them up, and divide by the number of values. The exclusion of NULLs from the denominator of the average operation is a little tricky:

SELECT (IFNULL(x, 0) + IFNULL(y, 0) + IFNULL(z, 0)) /
       (IIF(ISNULL(x), 0, 1) + IIF(ISNULL(y), 0, 1) + IIF(ISNULL(z), 0, 1))
  FROM YourTable


Try:

(x + y + z) / 3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜