0

I almost have what i need in the below query except there is another enddate_column in table3 i want to add to query. Right now it works great by if cardid is located in table3 it ignores where table1 and table2 do not equal. but i need to allow the query to return results even if table3 contains matching records as long as enddate_column is less than today.

SELECT * FROM [table1]
INNER JOIN [table2] ON [table1].MemberNum = [table2].MEMBERNUM
WHERE [table1].CardID<>[table2].cardid
AND EXISTS(SELECT * FROM [TABLE3] WHERE [TABLE3].CARDID<>[table1].CardID)

how to do i add that criteria.

scenario 1:
table1.cardid = 10005 table1.membernum = 9
table2.cardid = 10010 table2.membernum = 9
table3.cardid = 10005 table3.enddate = '2013-10-15'

This should return results for 10005 because even though table3.cardid is located table3.endate is less than today

scenario 2:
table1.cardid = 10005 table1.membernum = 9
table2.cardid = 10010 table2.membernum = 9
table3.cardid = 10005 table3.enddate = '2013-10-31'

this should not return results because cardid is located in table3 and enddate is greater than today.

scenario 3:
table1.cardid = 10005 table1.membernum = 9
table2.cardid = 10010 table2.membernum = 9
table3.cardid <>exist table3.enddate <> exist

this should return results of cardid 10005 because that id doesnt exist in table3

4

1 回答 1

0

I think you want something like this; left outer join to Table3 and to handle the missing row test for null rows by coalescing the date field with a faked yesterdays date.

SELECT 
    * 
FROM 
    [table1]

INNER JOIN [table2] 
ON [table1].MemberNum = [table2].MEMBERNUM

LEFT OUTER JOIN [Table3]
ON 
    table1.CardID = table3.CardID

WHERE 
    [table1].CardID<>[table2].cardid
AND (
    CAST(COALESCE(table3.enddate, DATEADD(dd,-1,GETDATE()) AS DATE) <= GETDATE()
    )
于 2013-10-19T14:40:50.640 回答