SQL有一个return = 0时返回的平均值

时间:2011-06-02 20:49:28

标签: mysql

我试图找到4回报a,b,c,d的平均值。有时一个返回ex a = 0,我想省略这个,只找到a,b,c的平均值

SELECT SUM(CASE WHEN x > 0 THEN COALESCE(a, 0) + COALESCE(b, 0) + COALESCE(c, 0) + COALESCE(d, 0)) / 4

请帮助!!!

2 个答案:

答案 0 :(得分:1)

Select Z.PrimaryKeyCol, Avg( Z.Value )
From    (
        Select PrimaryKeyCol, a As Value
        Union All Select PrimaryKeyCol, b
        Union All Select PrimaryKeyCol, c
        Union All Select PrimaryKeyCol, d
        ) As Z
Where Z.Value <> 0
Group By Z.PrimaryKeyCol

答案 1 :(得分:0)

select (a+b+c+d)
/
(if(a = 0,0,1) + if(b = 0,0,1) + if(c = 0,0,1) + if(d = 0,0,1) )
from table