您可以使用
window functions
. 显然你想请客
null
和只有空格的字符串是一样的,所以需要对它们进行规范化。
以下查询将生成所需的数字,如果单个字符串出现多次,还将提供信息:
select id, code,
row_number() over (partition by coalesce(nullif(trim(code),''),'') order by id) as counter,
count(*) over (partition by coalesce(nullif(trim(code),''),'')) as num_rows
from tablename
order by id;
通过示例输入,将返回:
id | code | counter | num_rows
---+------+---------+---------
1 | | 1 | 2
2 | | 2 | 2
3 | FOO | 1 | 2
4 | FOO | 2 | 2
5 | BAR | 1 | 2
6 | BOB | 1 | 1
7 | BAR | 2 | 2
表达式
coalesce(nullif(trim(code),''),'')
“正常化”
NULL
仅由空格组成的值和字符串,例如。
' '
到空字符串
''
.
现在可以使用它来更新表。由于您只想将计数器添加到多次出现的值,因此需要将更新限制为:
update tablename as tn
set code = concat(trim(tn.code), '(', x.counter, ')')
from (
select id, code,
row_number() over (partition by coalesce(nullif(trim(code),''),'') order by id) as counter,
count(*) over (partition by coalesce(nullif(trim(code),''),'')) as num_rows
from tablename
) x
where x.id = tn.id
and x.num_rows > 1;
更新后,您的示例如下所示:
id | code
---+-------
1 | (1)
2 | (2)
3 | FOO(1)
4 | FOO(2)
5 | BAR(1)
6 | BOB
7 | BAR(2)
联机示例:
http://rextester.com/WGAL85544