如何使用字段Postgres更新表

问题描述

我有这样的表:

enter image description here

Incident_id是外键。我想要实现的目标->再创建一个具有命名位置(int)的列。并按如下方式填充它:查找每个identity_id的所有行,并用我通过每个identity_id获得的行的索引或行列表更新每一行。例如: event_id 5与4条注释行匹配,因此位置的更新将相应地为0、1、2、3。 Ty

解决方法

我不建议存储这样的派生信息。相反,您可以创建一个使用row_number()来枚举每个incident_id的行的视图:

create view myview as
select t.*,row_number() over(partition by incident_id order by id) - 1 rn
from mytable t

要获得稳定的结果,您需要一个可用于一致地排列每个事件行的列:我在查询中将其称为id。您可以将其更改为您的用例的相关列名(或列集)。您通常会使用表的主键列。


编辑

如果您真的想在新列中实现该值,并考虑到表的主键,则可以执行以下操作:

alter table mytable add column position int;

update mytable t
set position = t1.position
from (
    select incident_note_id,row_number() over(partition by incident_id order by incident_note_id) - 1 position
    from mytable
) t1
where t1.incident_note_id = t.incident_note_id;