2015-11-05 50 views
0
Select drl.id, drl.ap, drl.sqn, drl.date 
from srs_drl drl 

在此就OUT輸出是這樣的:回到最早的記錄一組

14000001 01 01 05/11/2015 
14000001 01 01 06/11/2015 
14000001 01 01 01/12/2015 
14000001 01 01 04/01/2016 
15000234 01 02 05/11/2015 
15000234 01 03 06/11/2015 
15000234 01 03 01/12/2015 
15000234 01 04 04/01/2016 

對於每一個獨特的第一個3列,我需要找回的最早日期。因此,對於上表我希望返回:

14000001 01 01 05/11/2015 
15000234 01 02 05/11/2015 
15000234 01 03 06/11/2015 
15000234 01 04 04/01/2016 

任何幫助這個查詢將不勝感激。我試過使用TOP,但只返回整個表的第一條記錄,而不是第一個3列分組的第一條記錄。

在此先感謝

回答

2

做一個GROUP BY結合MIN

Select drl.id, drl.ap, drl.sqn, MIN(drl.date) 
from srs_drl drl 
group by drl.id, drl.ap, drl.sqn 

或者,NOT EXISTS返回行,如果沒有一個具有相同drl.id,drl.ap,drl.sqn是甚至更早:

Select drl.id, drl.ap, drl.sqn, drl.date 
from srs_drl drl 
where not exist (select 1 from from srs_drl d2 
       where d2.id = drl.id 
        and d2.ap = drl.ap 
        and d2.sqn = drl.sqn 
        and d2.date < drl.date) 

注意,日期是ANSI SQL的保留字,所以你可能需要寫"date"

+0

或在方括號中包裹'日期' - 'drl。[date]' – InbetweenWeekends

+0

那些d * mn方括號...是的,它們也適用。 – jarlh

+0

謝謝jarlh!我使用了GROUP BY,它工作得很好。非常感謝,實質上這是一個很容易解決的問題,我只是有一個真正的思想空白 - 在一天的工作結束時,這並沒有幫助它在16:45。 – gb332