如何在列为空的情况下使用递增的值更新 table?

How to update a table with incrementally increased values where a column is null?

我有一个包含两列的 table,namenumbernumber 列中的一些值为空。

name | number
-------------
a    | 11  
b    | null   
c    | null

我想在 number 列中找到最大值并用递增的值填充缺失值,如下所示 table:

name | number
-------------
a    | 11  
b    | 12  
c    | 13

我如何在 Postgresql 中执行此操作?

对于此示例数据,您可以在可以加入 table:

的查询中使用 MAX()ROW_NUMBER() window 函数
UPDATE tablename t1
SET number = t2.max_number + t2.rn
FROM (
  SELECT *,
         MAX(number) OVER () max_number,
         ROW_NUMBER() OVER (PARTITION BY number ORDER BY name) rn
  FROM tablename
) t2
WHERE t2.name = t1.name AND t1.number IS NULL;

参见demo

以防万一所有数字都是NULL,更改为:

SET number = COALESCE(t2.max_number, 0) + t2.rn