0

Apologies for the bad title, im at the beginner level.

The issue is this, i have a table of sold item counts, grouped by item type, month and year. Now if i run the query below:

SELECT YEAR(S.SellDate) AS Year, 
       MONTH(S.SellDate) AS Month, 
       T.ID as ProdType, 
       T.[Description] as ProdDescription, 
       COUNT(T.ID) AS Sold
FROM Items S
       RIGHT JOIN Types T on S.TypeID = T.ID
WHERE YEAR(S.SellDate) = 2022 
GROUP BY YEAR(SellDate), MONTH(SellDate), T.ID, T.[Description]
ORDER BY 1, 2, 3 ASC

I get the following table, notice how there are "missing" rows due to that type of item not being sold. I've tried different join types to no avail. The goal would be to list all items types with NULL or 0 if there no sale of that item was made.

Result:

Result

The goal would be

Goal

Thanks in advance.

1
  • Outer join a calendar table/cte to get missing months too. Commented Mar 8, 2023 at 10:23

1 Answer 1

0

Try using this. SQL Server JOIN missing NULL values

SELECT YEAR(S.SellDate) AS Year, MONTH(S.SellDate) AS Month, T.ID as ProdType, T.[Description] as ProdDescription, COUNT(T.ID) AS Sold

FROM Items S left JOIN Types T on S.TypeID = T.ID WHERE YEAR(S.SellDate) = 2022

GROUP BY YEAR(SellDate), MONTH(SellDate), T.ID, T.[Description]

ORDER BY 1, 2, 3 ASC

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.