对于令人困惑的标题感到抱歉。
我在这张桌子上:
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/2014
到3/5/2014
我应该:
ApplicantID Applicant Name
-------------------------------
3 Philip
4 Jerin
这意味着主表中必须位于第二个表中的申请人以及第二个表的最高日期必须属于指定的日期范围。希望情景很清楚。
答案 0 :(得分: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
答案 1 :(得分:1)
您需要在子查询中使用MAX
每个ApplicantId
提取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'