问题
I have the following table
recordID createdDate ForeignKeyID
00QA000000PtFXaMAN 2012-01-03 13:23:36.000 001A000000ngM21IAE
00QA000000OS2QiMAL 2011-12-15 12:03:02.000 001A000000ngM21IAE
.
.
.
.
I am trying to get the recordID for foreignKeyID where createdDAte is the min(createdDate) for foreignKeyID
if recordID is identity int I can get that by doing the following query
Select min(recordId),ForeignkeyID
from table
group by ForeignKeyId
I originaly thought that I can create temp table with the following query and then joining it to table on minDate and foreignKeyID but then I found out that there are multiple records for foreignKeyId that has the same exact createdDate.
Select min(createdDate) as minDate,ForeignKeyID
from table
group by ForeignKeyId
I'm open with using temp table or subquery or anything really. Thanks.
回答1:
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
回答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 ;
来源:https://stackoverflow.com/questions/13652828/how-do-i-get-the-record-id-of-the-record-with-the-min-date-for-each-foreign-key