How to select distinct records based on condition

谁说我不能喝 提交于 2019-12-26 18:14:06

问题


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


来源:https://stackoverflow.com/questions/26484634/how-to-select-distinct-records-based-on-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!