SELECT p.ID, Name
FROM Policies p
INNER JOIN ProgramYears py ON p.ProgramYearID = py.id
INNER JOIN (SELECT MemberID, max(EffectiveDate) AS EffectiveDate
FROM Policies
GROUP BY MemberID) TEMP
ON p.memberid = TEMP.MemberID
AND p.EffectiveDate = TEMP.effectivedate
AND p.memberid NOT IN (SELECT MemberID
FROM InvoiceDetail
WHERE ProgramYear = NAME)
答案 0 :(得分:1)
NOT EXISTS
通常是NOT IN
的更好替代品,但您的选择很大程度上取决于数据以及表和索引的结构。
尝试下面的查询,但将其执行计划与当前查询的执行计划进行比较;对一个场景有效的方法可能不适用于另一个场景。
SELECT p.ID, Name
FROM Policies p
INNER JOIN ProgramYears py ON p.ProgramYearID = py.id
INNER JOIN (SELECT MemberID, max(EffectiveDate) AS EffectiveDate
FROM Policies
GROUP BY MemberID) TEMP
ON p.memberid = TEMP.MemberID
AND p.EffectiveDate = TEMP.effectivedate
WHERE NOT EXISTS
(SELECT MemberID
FROM InvoiceDetail AS ID
WHERE ID.ProgramYear = NAME
AND p.MemberId = ID.MemberId)
答案 1 :(得分:0)
您可以尝试:
SELECT a.ID, a.Name
FROM (SELECT p.ID, Name,
ROW_NUMBER()OVER(PARTITION BY p.memberid ORDER BY p.EffectiveDate DESC) AS rnk
FROM Policies p
INNER JOIN ProgramYears py ON p.ProgramYearID = py.id
WHERE NOT EXISTS (SELECT MemberID
FROM InvoiceDetail AS ID
WHERE ID.ProgramYear = NAME
AND p.MemberId = ID.MemberId)
) a
WHERE a.rnk = 1