我想做的是返回所有拥有enddate <= GETDATE()
的人,但我需要首先从MAX(enrollmentID)
表中读取managementTempTable
。
这是我到目前为止的内容:
select personID, firstName, lastName, [GUID], ouPath
from managementTable
where personID in
(
select personID
from
(
select personID
from managementTempTable
where endDate <= GETDATE()
group by personID
) as tbl
)
and accountEnabled = 1
我知道这行不通,因为它返回具有endDate <= GETDATE()
的数据行。它需要读取MAX(enrollmentID)
,然后评估是否endDate <= GETDATE()
。
managementTempTable
中的数据如下:
enrollmentID,personID,firstName,lastName,endDate
61490,18213,John,Doe,8/23/2018
64766,18213,John,Doe,NULL
64720,18570,Jane,Doe,10/18/2018
64862,18570,Jane,Doe,NULL
所需结果如下:
enrollmentID,personID,firstName,lastName,endDate
64766,18213,John,Doe,NULL
64862,18570,Jane,Doe,NULL
答案 0 :(得分:2)
为什么不使用row_number()
? :
select mt.*
from (select mt.*,
row_number() over (partition by personid order by enrollmentID desc) as seq
from managementTable mt
where . . .
) mt
where mt.seq = 1;
答案 1 :(得分:2)
如果您想按MAX
来获得enrollmentID
行,可以尝试在where
中使用子查询
SELECT t1.*
FROM managementTempTable t1
WHERE enrollmentID = (
SELECT MAX(enrollmentID)
FROM managementTempTable tt
WHERE t1.personID = tt.personID
)
答案 2 :(得分:0)
这将为您提供帮助
SELECT *
FROM managementTempTable
WHERE enrollmentID in (
Select max(enrollmentID) EId
FROM managementTempTable
where isnull(enddate,getdate()) <= Getdate()
group by PersonId)