如何根据PostgreSQL中相同行的两个不同列更新具有唯一序列号的列?

问题描述

我有以下格式(示例)的记录列表,通过连接数据库中的多个表和 where 条件生成

Col1 Col2 Col3
100 200 1
100 201 1
100 202 1
100 203 1
101 204 1
101 205 1
102 206 1
102 207 1

我想要的是根据 Col1 和 Col2 中的值更新上例中 Col3 中的值。

这个想法是先循环通过 Col1,然后在 Col2 中进行另一个循环,并从 1 开始更新 Col3 中的值,并在 Col2 记录上每次迭代增加 1。对于 Col1 的下一次迭代,应再次重复此操作。

上述方法的预期输出示例是:

Col1 Col2 Col3
100 200 1
100 201 2
100 202 3
100 203 4
101 204 1
101 205 2
102 206 1
102 207 2

使用的数据库是 postgres,我对 postgres 中的游标等功能很陌生。 如果有人对此有任何见解以有效地解决此问题,那就太好了。

感谢您的帮助。

谢谢

解决方法

您可以使用 row_number()over() 排名窗口函数轻松实现这一点:

架构和插入语句:

 create table table1(Col1 int,Col2    int,Col3 int);
 insert into table1 values(100,200,1);
 insert into table1 values(100,201,202,203,1);
 insert into table1 values(101,204,205,1);
 insert into table1 values(102,206,1);

更新查询:

 with cte as(
    select col1,col2,col3,row_number()over (partition by col1 order by col2) rn from table1
 )
 update table1 set col3=cte.rn
 from cte
 where table1.col1=cte.col1 and table1.col2=cte.col2;

在上面的查询中,row_number()over (partition by col1 order by col2) 将为 col1 中的每个不同值生成一个唯一序列,从 1 开始并按 col2 排序。

选择查询:

 select * from table1;

输出:

col1 col2 col3
100 200 1
100 201 2
100 202 3
100 203 4
101 204 1
101 205 2
102 206 1

dbfiddle here

,

您可以借助相关计数子查询来表达更新:

UPDATE yourTable t1
SET Col3 = (SELECT COUNT(*) FROM yourTable t2
            WHERE t2.Col1 = t1.Col1 AND t2.Col2 <= t1.Col2);

您使用的实际查询可能比上面稍微复杂一些,假设您向我们展示的输出是由连接产生的。但是,您应该能够遵循相同的模式。请注意,我的回答还假设与每个 Col2 值关联的 Col1 值始终是唯一的。