gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:22:26 25 4
gpt4 key购买 nike

我有下表

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 的最小(创建日期)

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

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

我最初认为我可以使用以下查询创建临时表,然后将其加入 minDate 和 foreignKeyID 上的表,但后来我发现 foreignKeyId 有多个记录具有完全相同的创建日期。

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

我愿意使用临时表或子查询或其他任何东西。谢谢。

最佳答案

其中一种方法是

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

因为代码短,我比其他人更喜欢第二个

关于sql - 如何使用每个外键的最小日期获取记录的记录 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13652828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com