I have a SQL query which pulls unit sales by item, by week:
SELECT sls_vendor,
sls_item,
sls_units,
DATEPART(week, sls_week) AS sls_date
FROM mytable
Assume I’m looking at a 8 week period, but not every item/vendor combination has a full 8 weeks of sales. However I need my query to show a null value in that instance. So the query would return 8 rows for each item/vendor combination regardless of existence.
I tried creating a temp table which has the numbers 28 to 35 and performing a left join on the query above, but that doesn’t show null values. The results are no different than running the original query alone.
I can think of how this would be done using a crosstab/pivot query, but isn’t this something the join should be doing?
Edit: Updated to show my join query. Datetable just has 8 rows with 1 incremental number for each calendar week.
SELECT * FROM @datetable
LEFT JOIN
(SELECT
sls_vendor,
sls_item,
sls_units,
datepart(week,sls_week) AS sls_date
FROM mytable) AS QRY
ON temp_week = qry.sls_date
Your method should work just fine:
Output:
Edit: If you want to include all week values for every sales vendor, include a cross join with the distinct selection of vendors:
Output: