我需要这个sql来更新具有重复名称的每一行,其值为name(自动增加的数字)。例如,三行的名称如下:
name
name
name
我需要将它们更新为:
name(1)
name(2)
name(3)
代替。
我设法成功创建了一个SELECT语句。我真的在努力将其转换为实际更新。请帮忙。
我的SQL:
SELECT id,name
,CASE WHEN (count(*) OVER (PARTITION BY name)) > 1 THEN
regexp_replace(name, '(.*)',
'\1('
|| row_number() OVER (PARTITION BY name ORDER BY id)
|| ')'
)
ELSE name END AS name
FROM public.table
ORDER BY public.table.name;
我正在使用Postgres btw。
在此处发布工作解决方案:
WITH c as (
SELECT id,name AS y
,CASE WHEN (count(*) OVER (PARTITION BY name)) > 1 THEN
regexp_replace(name, '(.*)',
'\1('
|| row_number() OVER (PARTITION BY name ORDER BY id)
|| ')'
)
ELSE name END AS name
FROM public.table
ORDER BY public.table.name
)
UPDATE public.table AS t
SET name = c.name
FROM c
WHERE t.id = c.id
;
答案 0 :(得分:0)
尝试update from
:
with c as (
SELECT id,name as name_o
,CASE WHEN (count(*) OVER (PARTITION BY name)) > 1 THEN
regexp_replace(name, '(.*)',
'\1('
|| row_number() OVER (PARTITION BY name ORDER BY id)
|| ')'
)
ELSE name END AS name
FROM public.table
ORDER BY public.table.name
)
update public.table t
set t.name = c.name
from c
where t.id = c.id
;
当然在交易中 - 我无法检查声明