2

我有下表

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

我对使用临时表或子查询或其他任何东西持开放态度。谢谢。

4

2 回答 2

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 提琴示例

另一种方法是

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 提琴示例

还有另一种方式

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 提琴示例

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

于 2012-11-30T20:42:41.083 回答
2
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 ;
于 2012-11-30T20:49:47.417 回答