MySQL平均非空列

时间:2015-04-01 11:17:40

标签: mysql

我已经通过这样做了,但我觉得可能有更清洁/更快/更好的解决方案,我总是热衷于学习:

UPDATE myTable SET fAvg =

(COALESCE(f1,0) + COALESCE(f2,0) + COALESCE(f3,0) + COALESCE(f4,0))

/

(
CASE WHEN f1 IS NOT NULL THEN 1 ELSE 0 END + 
CASE WHEN f2 IS NOT NULL THEN 1 ELSE 0 END + 
CASE WHEN f3 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN f4 IS NOT NULL THEN 1 ELSE 0 END 
)

那么,如何改进?

1 个答案:

答案 0 :(得分:0)

您可以利用MySQL在数字上下文中将布尔值视为整数这一事实来简化计数:

UPDATE myTable
    SET fAvg = (COALESCE(f1,0) + COALESCE(f2,0) + COALESCE(f3,0) + COALESCE(f4,0)) /
               ((f1 IS NOT NULL) + (f2 IS NOT NULL) + (f3 IS NOT NULL) + (F4 IS NOT NULL));