3 ms·
I get the idea that not too many people know how to use window functions, even though they're a slick solution to some potentially messy problems. I've used the
by ufmace 12y ago
I get the idea that not too many people know how to use window functions, even though they're a slick solution to some potentially messy problems. I've used them several times to deal with duplicate data issues.
Got a table where you want to put a unique index on a column that has some duplicate values? It's a pretty easy fix to use a window query along with group by and having to get a list of rows with duplicate entries for the column and use row_number to assign a unique number to each duplicate. Then, use string concat to tack that number onto the end of the string. Select the new string and the item ID, put it in a CTE, and connect it to an update query to actually change all the names in one query.
Goes kinda like this:
with DrawingDupes as
(select d.DrawingId, d.RevTag,
'_DUPLICATE_' + cast((ROW_NUMBER() over (partition by d.Number, d.RevTag, d.UnitId order by d.DrawingId)) as varchar) NewX
from (select Number, RevTag, UnitId
from Drawing group by Number, RevTag, UnitId having COUNT(*) > 1) t join Drawing d
on d.Number = t.Number and d.RevTag = t.RevTag and d.UnitId = t.UnitId)
update DrawingDupes set RevTag = RevTag + NewX;