Skip to content
Advertisement

Mark existing rows as duplicates when selecting with left join in T-SQL

I am trying to do a LEFT JOIN to merge a table and view and the right table has duplicate items(usernames). I want to keep them but add another column to mark them as isDuplicate='TRUE'.

I wanted to use CASE WHEN EXISTS but can’t get it to work correctly, it produces wrong results:

Ideally I would like to not mark the first occurence of a row as duplicate. E.g. first time username appears it is not marked as duplicate, second time it is a duplicate. If not possible then just mark all rows that don’t have unique usernames as isDuplicate='TRUE'.

Example data:

View:

Table:

Expected result:

Alternative option if first is not possible:

Advertisement

Answer

I think you want row_number() or count(*). To tag all duplicate user names:

You would use row_number() . . . = 1 if you wanted to identify as duplicates all but one of the duplicates.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement