根据一列选择前2名?

时间:2016-02-03 14:52:16

标签: sql sql-server

我的表看起来像这样:

Name    LastN   DOB    EntryDate<br>
John    Smith   2015   21/02/2012<br>
John Smith      2015   26/04/2012<br>
John Smith      2015   27/05/2012<br>
Karen Eps 2015        29/08/2012<br>
Karen Eps 2015        23/05/2014<br>
Karen Eps 2015        12/02/2012


我需要一个查询,为每个名字提取2个最新日期?所以输出看起来像是:

Name    LastN   DOB    EntryDate<br>
John Smith      2015   26/04/2012<br>
John Smith      2015   27/05/2012<br>
Karen Eps 2015        29/08/2012<br>
Karen Eps 2015        23/05/2014<br>


非常感谢您对此的任何帮助!请善待,我是SQL新手:)

2 个答案:

答案 0 :(得分:3)

最简单的方法是row_number()

select t.*
from (select t.*,
             row_number() over (partition by Name, LastName order by EntryDate desc) as seqnum
      from mytable t
     ) t
where seqnum <= 2;

答案 1 :(得分:0)

    select distinct firstname,lastname,b.*
             from yourtable t
                             cross apply(
                                select top 2 entrydate from yourtable t1
                               where t1.firstname=t.firstname                                        
                                         and t1.lastname=t.lastname 
                                             order by entrydate desc)b