SQL Server Select the most recent record only

前端 未结 1 568
借酒劲吻你
借酒劲吻你 2021-01-16 02:51

I have a table tat looks like this:

Table1

ID Date       TermDate Cancel
1  20140101   99999999 20140102
1  20140101   20130102 20140102

2  20140108         


        
1条回答
  •  说谎
    说谎 (楼主)
    2021-01-16 03:34

    You can use dense_rank function to assign a rank to each row within one ID based on your ordering and get the first one for each ID:

    select id, [date], termdate, cancel from
        (select id, [date], termdate, cancel,
            dense_rank() over (partition by id order by [date] desc, cancel desc, termdate desc) rank
        from table1) X
    where rank = 1
    

    SQL Fiddle Demo

    0 讨论(0)
提交回复
热议问题