2014-11-21 26 views
0

對於令人困惑的標題,抱歉。根據日期範圍內的子表中的最高日期從主表中選擇行

我有這個表:

ApplicantID Applicant Name 
------------------------------- 
1    Sandeep 
2    Thomas 
3    Philip 
4    Jerin 

隨着其與上表中連接該子表:

DetailsID  ApplicantID  CourseName  Dt 
--------------------------------------------------------------------- 
1     1    C1    10/5/2014 
2     1    C2    10/18/2014 
3     1    c3    7/3/2014 
4     2    C1    3/2/2014 
5     2    C2    10/18/2014 
6     2    c3    1/1/2014 
7     3    C1    1/5/2014 
8     3    C2    4/18/2014 
9     3    c3    2/23/2014 
10     4    C1    3/15/2014 
11     4    C2    2/20/2014 
12     4    C2    2/20/2014 

我想applicantsID,例如,當我指定日期範圍從 4/20/20143/5/2014我應該有:

ApplicantID Applicant Name 
------------------------------- 
3    Philip 
4    Jerin 

這意味着主表中的申請人必須在第二個表格中,也是第二個表格的最高日期必須落在指定的日期範圍內。希望情況很清楚。

+1

你試過什麼了嗎?你能告訴我們你有什麼嗎? – bowlturner 2014-11-21 15:58:13

+0

看起來相當直接,你到目前爲止嘗試過什麼? – Andrew 2014-11-21 15:58:14

+0

究竟是什麼問題?你嘗試過什麼嗎? – tinySandy 2014-11-21 15:59:20

回答

1

您需要將ApplicantIdMAX拉到GROUP BY的子查詢中,然後JOIN得到該結果。這應該爲你工作:

Select A.ApplicantId, A.[Applicant Name] 
From ApplicantTableName A 
Join 
(
    Select D.ApplicantId, Max(D.Dt) DT 
    From DetailsTableName D 
    Group By D.ApplicantId 
) B On A.ApplicantId = B.ApplicantId 
Where B.DT Between '03/05/2014' And '04/20/2014' 
3

您可以使用窗口解析函數row_number讓申請人在指定時間內的最大日期。

select T1.[ApplicantID], [Applicant Name] 
from Table1 T1 
join (select [ApplicantID], 
       ROW_NUMBER() over (partition by [ApplicantID] order by Dt desc) as rn 
     from Table2 
     where Dt BETWEEN '3/5/2014' AND '4/20/2014' 
    ) T 
on T1.[ApplicantID] = T.[ApplicantID] 
and T.rn =1 
相關問題