How do I get the record ID of the record with the min date for each foreign key?

血红的双手。 提交于 2019-12-02 02:11:48

One of the ways to do it is

select A.ForeignKeyID, R.recordID
from (select distinct t.ForeignKeyID from table as t) as A
    outer apply
    (
        select top 1 t.recordID
        from table as t where t.ForeignKeyID = A.ForeignKeyID
        order by t.createdDate asc
    ) as R

SQL FIDDLE EXAMPLE

Another way to do it is

select top 1 with ties
    t.recordID, t.ForeignKeyID
from table as t
order by row_number() over (partition by t.ForeignKeyID order by t.createdDate)

SQL FIDDLE EXAMPLE

And another way

select A.recordID, A.ForeignKeyID
from
(
    select
        t.recordID, t.ForeignKeyID,
        row_number() over (partition by t.ForeignKeyID order by t.createdDate) as RowNum
    from table1 as t
) as A
where A.RowNum = 1

SQL FIDDLE EXAMPLE

I like second one more than others because of shortness of code

SELECT 
    recordID, createdDate, ForeignKeyID
FROM
  ( SELECT 
        recordID, createdDate, ForeignKeyID,
        ROW_NUMBER() OVER ( PARTITION BY ForeignKeyID 
                            ORDER BY createdDate, recordID
                          ) AS rn
    FROM 
        tableX
  ) AS t
WHERE 
    rn = 1 ;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!