简体   繁体   中英

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?

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.

In this case the output is

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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