sql - 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值。有什么建议吗?
解决方案
这是做你想做的吗?
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
,其增量值超过了先前的最大值。
推荐阅读
- c# - 对 Visual Studio Code 使用的 C# 版本感到困惑
- c# - “对象 '%' 不是序列对象”错误
- django - 有没有最简单的方法来异步运行 python 请求的数量?
- sql - LINQToSQL - 提供自动递增 ID - 行不在数据库中
- spring - 为某些服务设置呼叫限制
- azure-java-sdk - 使用 SqlDatabase.createAsync() 创建时设置数据库属性
- c# - c#某些单词后的值正则表达式
- ms-access - 如何使用查询汇总列
- android - 从另一个应用程序读取存储在内部存储中的图像
- google-chrome - 谷歌浏览器不为 CORS 请求附加 Cookie?