如何获取每个外键的最小日期记录的记录ID?

时间:2012-11-30 20:39:55

标签: sql sql-server-2008 tsql group-by greatest-n-per-group

我有下表

recordID               createdDate                         ForeignKeyID
00QA000000PtFXaMAN     2012-01-03 13:23:36.000             001A000000ngM21IAE
00QA000000OS2QiMAL     2011-12-15 12:03:02.000             001A000000ngM21IAE
.
.
.
.

我正在尝试获取foreignKeyID的recordID,其中createdDAte是foreignKeyID的min(createdDate)

如果recordID是identity int,我可以通过执行以下查询来获取

Select min(recordId),ForeignkeyID
from table 
group by ForeignKeyId

我原本以为我可以使用以下查询创建临时表,然后将其连接到minDate和foreignKeyID上的表,但后来我发现有多个foreignKeyId记录具有完全相同的createdDate。

Select min(createdDate) as minDate,ForeignKeyID
from table
group by ForeignKeyId

我打开使用临时表或子查询或其他任何东西。感谢。

2 个答案:

答案 0 :(得分:3)

其中一种方法是

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

另一种方法是

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

另一种方式

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

由于代码短缺,我比其他人更喜欢第二个

答案 1 :(得分:1)

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 ;