adsense

Sunday, November 8, 2020

sql server remove duplicates from query

You can use SQL row_number() function to remove duplicate rows from a query.

Create table Employees (fname varchar(100), lname varchar(100))

Insert into Employees Values 
               ('Tim', 'May')
             , ('Clara', 'Magrette') 
             , ('Clara', 'Magrette')
             , ('Jeff', 'Lawry') 
             , ('Brian', 'Adams')
             , ('Paul', 'Oliver')

As you can see there are duplicate records in the Employees table,

Select * from(
SELECT fname 
       ,lname 
       ,row_number() over (partition by fname , lname order by fname , lname ) as rownum 
FROM Employees 
) result
where rownum= 1 -- selects DISTINCT Employees only

Cheers,
Samitha

No comments:

Post a Comment