I am having an issue with my selection. I need to return the old rank if the PaymentDate less than the datestamp from Log_Promotion, but I can’t seem to get it to return the correct record. Not all Customers are in the Table Log_Promotion
OrderID 1000285 = should be OldRankID = 1
OrderID 1000539 = should be OldRankID = 2
OrderID 1000581 = should be OldRankID = 2
OrderID 1000611 = should be OldRankID = 3
Table Log_Promotion
CustomerID OldRankID NewRankID CommissionPeriod datestamp
9082958342 1 2 201509 2015-09-21 18:11:43.543
9082958342 2 3 201509 2015-09-21 19:45:59.100
Table Orders
OrderID CustomerID PaymentDate
1000285 9082958342 2015-09-21 17:11:43.543
1000539 9082958342 2015-09-21 19:18:54.123
1000581 9082958342 2015-09-21 19:41:59.100
1000611 9082958342 2015-09-21 20:17:24.173
MSSQL
IIF(lp.datestamp IS NULL,c.RankID,lp.OldRankID) FROM Customers c WITH (NOLOCK) LEFT JOIN Log_Promotion lp WITH (NOLOCK)
ON (lp.CustomerID = c.CustomerID AND @PaymentDate <= lp.datestamp) WHERE c.CustomerID = 9082958342)