sql server - Appending charactes to a string when duplicate found -
say have table of ids, names , field flag update follows:
+----+-------+---------+ | id | name | update? | +----+-------+---------+ | 1 | | y | | 2 | b | y | | 3 | xxb | | | 4 | c | | | 5 | d | y | | 6 | xxd | | | 7 | xxxd | | | 8 | e | | +----+-------+---------+ the 'update' append 'xx' name, there cannot duplicate names in table i'd append additional 'x' duplicates found. 1 table update this:
+----+-------+---------+ | id | name | update? | +----+-------+---------+ | 1 | xxa | | | 2 | xxb | | | 3 | xxxb | | | 4 | c | | | 5 | xxd | | | 6 | xxxd | | | 7 | xxxxd | | | 8 | e | | +----+-------+---------+ any ideas on best way this? updating of duplicates occur initial update i'm stuck on, , i'm not sure how easy have check on , update levels of duplication, eg no duplicate, b 1 level, d 2 levels etc.
thanks, dave
try one:
with cteupdate as( select *, base = replace(name, 'x', ''), xxname = replicate('x', row_number() over( partition replace(name, 'x', '') order id ) + 1 ) + replace(name, 'x', '') testdata replace(name, 'x', '') in( select name testdata [update] = 1 ) ) update cteupdate set name = xxname , [update] = 0 result:
id name update ----------- ---------- ------ 1 xxa 0 2 xxb 0 3 xxxb 0 4 c 0 5 xxd 0 6 xxxd 0 7 xxxxd 0 8 e 0 first, want rows have same base name (the name minus xxs) rows update = 1. base name, replace x '':
select *, base = replace(name, 'x', '') testdata replace(name, 'x', '') in( select name testdata [update] = 1 ) the result of above be:
id name update base ----------- ---------- ------ ------ 1 1 2 b 1 b 3 xxb 0 b 5 d 1 d 6 xxd 0 d 7 xxxd 0 d then, want use row_number over(partition base order id). resulting row_number + 1 number of xs added on base
with cteupdate as( select *, base = cast(replace(name, 'x', '') varchar(1)) testdata replace(name, 'x', '') in( select name testdata [update] = 1 ) ) select rn = row_number() over(partition base order id), xxname = replicate('x', row_number() over(partition base order id) + 1) + base cteupdate the result of query above be:
id name update base rn xxname ----------- ---------- ------ ------ ----- --------- 1 1 1 xxa 2 b 1 b 1 xxb 3 xxb 0 b 2 xxxb 5 d 1 d 1 xxd 6 xxd 0 d 2 xxxd 7 xxxd 0 d 3 xxxxd the xxname updated name.
Comments
Post a Comment