PostgreSQL - 查找和更新多个记录

时间:2016-02-23 18:57:35

标签: sql postgresql

我有一张桌子:

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    

我希望有类似的东西:

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  

如何找到多重ID值以使其唯一?

如何在?

之后更新父表

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

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"
  

我假设你不能拥有两行同样IDrows的其他行,你需要在"dimensions"包含WHERE

在这种情况下输出为

enter image description here