首页 > 解决方案 > PostgreSQL:如果以下为NULL,则在+1列中设置最大值

问题描述

我是 SQL 的新手,我知道以下问题很受欢迎,但任何建议的解决方案都对我没有帮助。所以,我有一张桌子

ratingId | userId
1        | 1
2        | 2
NULL     | 3
NULL     | 4

现在我想为每一行设置 '3'、'4' 等而不是 NULL ratingId = NULL,这意味着最后一个 NOT NULL 值的 MAX 值 + 1

我用过很多方法,但最流行的是max()

我目前的代码是

SELECT
    COALESCE(rating.id, max(rating.id)) AS id,

但它不起作用:(我仍然有NULL值。有什么建议吗?

标签: sqlpostgresql

解决方案


这是做你想做的吗?

select coalesce(ratingId,
                coalesce(max(ratingId) over (), 0) +
                         count(*) filter (where ratingId is null) over (order by userid)
               ) as imputed_ratingId

一个等效的措辞是:

select coalesce(ratingId,
                coalesce(max(ratingId) over (), 0) +
                         row_number() over (partition by ratingId order by userid)
               ) as imputed_ratingId

ratingId这些为它所在的行提供了唯一性NULL,其增量值超过了先前的最大值。


推荐阅读