2012-11-30 100 views
2

我有以下表如何獲取每個外鍵的最短日期記錄的記錄ID?

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

我想獲得的recordId爲foreignKeyID其中createdDAte是foreignKeyID

最小(createdDate)如果的recordId是身份的詮釋我可以通過執行以下操作查詢

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

我的淵源以爲我可以創建以下查詢臨時表,然後在的minDate和foreignKeyID其連接到表,但後來我發現,有對foreig多個記錄nKeyId具有相同的createdDate。

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

我打開使用臨時表或子查詢或任何真的。謝謝。

+0

這個問題已經在過去已經回答了很多次,因爲代碼急促別人多一個:http://stackoverflow.com/questions/tagged/most-n-group-group + sql-server –

+0

@BillKarwin感謝您指出這一點,我很難找出如何搜索問題。我嘗試了幾次,但沒有拿出我需要的東西。 – atbebtg

回答

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

我喜歡第二比

+0

哇@roman非常感謝你。第一個工作很好,我會檢查其他2。 – atbebtg

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 ; 
相關問題