Link to home
Start Free TrialLog in
Avatar of Jimbo99999
Jimbo99999Flag for United States of America

asked on

SQL Query - Trouble with null Date and Join

Hello There Experts!

I am having a bit of trouble with my query.  I am LEFT JOINING to a table.

DECLARE @passedInOrderDatedate = '2017-08-01'
Select * from Customer LEFT JOIN Order where orderDate > @passedInOrderDate

Need to find:
1) Customers that do not have records that have an orderDate > @passedInOrderDate
2) Customers that do not have any Order records at all

Please ask questions as I have already taken too much time to solve this on my own.

Thanks,
jimbo99999
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

For starters, you are missing the ON clause that spells out how Customer and Order are related.

SELECT * 
FROM Customer 
   LEFT JOIN Order ON Customer.??? = Order.???
WHERE orderDate > @passedInOrderDate

Open in new window

Assuming the above is figured out, and using some air code..

-- 1) Customers that do not have records that have an orderDate > @passedInOrderDate
SELECT * 
FROM Customer 
   LEFT JOIN Order ON Customer.CustomerID = Order.CustomerID
WHERE CustomerID NOT IN (SELECT DISTINCT CustomerID FROM Customer WHERE orderDate > @passedInOrderDate

-- 2) Customers that do not have any Order records at all 
SELECT * 
FROM Customer 
   LEFT JOIN Order ON Customer.CustomerID = Order.CustomerID
WHERE Order.CustomerID IS NULL

Open in new window

Both in one query:

DECLARE @passedInOrderDate DATE = '20170801';

SELECT C.*
FROM   PayPerClick.Customers C
       LEFT JOIN Orders O ON O.CustomerID = C.CustomerID
                             AND O.orderDate > @passedInOrderDate
WHERE  O.OrderID IS NULL;

Open in new window


p.s. use unambiguous date literals!
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jimbo99999

ASKER

Thank you all for your help.  I ended up working with Scott's or in the where.  But I wanted to say thanks to everyone for their responses.  

jimbo99999
Well, just compare the execution plans..