I am trying to join two tables in SQL, one containing a list of items, and the other with the dates they were sold. I got the join part down, but I need to get the information from the REPORT table, but all items in the VENDORS table. I need the items that were not sold to show up as NULL, or preferably 0. This is the code I’m using so far, and it’s only showing the items that were sold on the given day.
SELECT t2.[DATE]
,t1.[VENDOR]
,t1.[UPC]
,t2.[QTY]
,t2.[AMOUNT]
FROM [STORESQL].[dbo].[VENDORS] t1
LEFT OUTER JOIN [STORESQL].[dbo].[REPORT] t2 ON t1.UPC=t2.UPC
WHERE VENDOR='119828' AND DATE='2011-11-8'
and example of the tables are
VENDORS:
VENDOR UPC
119828 1
119828 2
119828 3
REPORT:
DATE UPC QTY AMOUNT
2011-11-8 1 1 9.99
2011-11-8 3 2 18.98
The current code is resulting in
DATE VENDOR UPC QTY AMOUNT
2011-11-8 119828 1 1 9.99
2011-11-8 119828 3 2 18.98
I need it to show
DATE VENDOR UPC QTY AMOUNT
2011-11-8 119828 1 1 9.99
2011-11-8 119828 2 0 0.00
2011-11-8 119828 3 2 18.98
I know i’m doing something wrong, but I don’t know what that is.
Thanks in advance.
Try this instead:
The where clause against DATE makes your outer join to function as an inner join because the comparison will be against a null value in DATE. Moving the comparison to the ON clause should deal with that.
To get a 0 instead of null as a result you can use COALESCE:
Your date column will also be null and that can be fixed with COALESCE as well: