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.

jcf
  • 180
  • 9

1 Answers1

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

Maddy
  • 87
  • 5