How to select distinct records based on condition

2019-09-22 08:34发布

问题:

I have table of duplicate records like Now I want only one record from duplicate records which has latest created date as How can I do it ?

回答1:

use row_number():

select EnquiryId, Name, . . .
from (select t.*,
             row_number() over (partition by enquiryID order by CreatedDate desc) as seqnum
      from table t
     ) t
where seqnum = 1;


回答2:

Use ROW_NUMBER function to tag the duplicate records ordered by CreatedDate, like this:

;with CTE AS (
    select *, row_NUMBER() over(
                 partition by EnquiryID -- add columns on which you want to identify duplicates
                 ORDER BY CreatedDate DESC) as rn
    FROM TABLE 
)
select * from CTE
where rn = 1