4

I am trying to add a row number to duplicate records.

declare @tbl table
(col1 varchar(10),col2 varchar(10) )

insert into @tbl values ('a1','b1')

insert into @tbl  values('a1','b1')

insert into @tbl values ('a1','b2')


insert into @tbl  values('a2','b2')

insert into @tbl  values('a2','b2')
insert into @tbl  values('a2','b2')
insert into @tbl  values('a3','b3')
insert into @tbl  values('a3','b3')


select col1,col2,ROW_NUMBER() OVER(ORDER BY col1,col2 ) AS id from @tbl

The below is the expected result

declare @tbl1 table
(col1 varchar(10),col2 varchar(10),id int )

insert into @tbl1 values ('a1','b1',1)

insert into @tbl1  values('a1','b1',2)

insert into @tbl1 values ('a1','b2',1)


insert into @tbl1  values('a2','b2',1)

insert into @tbl1  values('a2','b2',2)
insert into @tbl1  values('a2','b2',3)
insert into @tbl1  values('a3','b3',1)
insert into @tbl1 values('a3','b3',2)

select * from @tbl1
Mureinik
  • 297,002
  • 52
  • 306
  • 350

2 Answers2

4

Try this you need to use partition by

SELECT col1,
       col2,
       Row_number()
         OVER(
           partition BY col1, col2
           ORDER BY col1, col2 ) AS id
FROM   @tbl 
Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
2

row_number will always give every row within the window a different value. If you want to detect duplicates, you need to use rank instead:

SELECT col1, col2, 
       RANK() OVER (PARTITION BY col1, col2 ORDER BY col1, col2) AS id 
FROM   @tbl

Or to query just the duplicates:

SELECT col1, col2
FROM   (SELECT col1, col2, 
               RANK() OVER (PARTITION BY col1, col2 ORDER BY col1, col2) AS id 
        FROM   @tbl) t
WHERE  id > 1
Mureinik
  • 297,002
  • 52
  • 306
  • 350