简体   繁体   English

PostgreSQL-查找和更新多个记录

[英]PostgreSQL - finding and updating multiple records

I have a table: 我有一张桌子:

ID | rows | dimensions
---+------+----------- 
1  |  1   |   15 x 20
2  |  3   |   2  x 10
3  |  5   |   23 x 33
3  |  7   |   15 x 23 
4  |  2   |   12 x 32    

And I want to have something like that: 我想要这样的东西:

ID | rows | dimensions
---+------+----------- 
1  |  1   |   15 x 20
2  |  3   |   2  x 10
3a |  5   |   23 x 33
3b |  7   |   15 x 23 
4  |  2   |   12 x 32  

How can I find the multiple ID value to make it unique? 如何找到多个ID值使其唯一?

How can I update the parent table after? 之后如何更新父表?

Thanks for your help! 谢谢你的帮助!

with stats as (
    SELECT "ID", 
           "rows",
           row_number() over (partition by "ID" order by rows) as rn,
           count(*) over (partition by "ID") as cnt
    FROM Table1
)
UPDATE Table1
   SET "ID" = CASE WHEN s.cnt > 1 THEN s."ID" || '-' || s.rn 
                   ELSE s."ID"
              END
  FROM stats s
 WHERE S."ID" = Table1."ID"
   AND S."rows" = Table1."rows"

I'm assuming you cant have two rows with same ID and same rows other wise you need to include "dimensions" on the WHERE too. 我假设你不能有两排相同的ID和同一rows等方面,需要包括"dimensions"WHERE了。

In this case the output is 在这种情况下,输出为

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM