查询计算平均值(包括NULL)

时间:2020-09-01 21:31:26

标签: mysql sql sql-update

我有如下查询:

UPDATE table SET result = ROUND((col1 + col2)/2, 2);

如果col1和col2中都存在一个值,则很好,但是如果其中一个为null,则返回null。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以这样做:

UPDATE table 
SET result = ROUND(
    (coalesce(col1, 0) + coalesce(col2, 0)
    / nullif( (col1 is not null) + (col2 is not null), 0), 
2);

分子将两列相加,同时将null的值变为0。分母计算不是null的值。换句话说,如果有两个非null值,则得到它们的平均值,而如果只有一个,则得到值本身。

如果两个值均为null,则result仍为null(这似乎是相关的操作)。