I have a table with fields like this:
Item
Category
Year
Month
Value
I want to aggregate the result from this table to display sum(value) for each category, year and month. So I have this query:
SELECT Category, Year, Month, SUM(Value)
FROM Table
GROUP BY Category, Year, Month;
This works fine, but for months in which the sum is zero, the month is not displayed. I want all months to be displayed with zero for the total value where applicable.
I’ve tried doing COALESCE(SUM(Value),0)
, but this didn’t work.
I’ve tried creating a separate table (Table2) with the year and month values and then joining this with the first table:
SELECT Category, Year, Month, SUM(Value)
FROM Table
RIGHT JOIN Table2
ON Table2.Year + Table2.Month = Table.Year + Table.Month
GROUP BY Category, Year, Month;
This doesn’t work either. What am I doing wrong?
Edit:
I have tried Dems's solution, using the following query:
SELECT
Category.name,
Dates.Year,
Dates.Month,
SUM(Data.Value) AS Value
FROM
Category
CROSS JOIN
Dates
LEFT JOIN
Data
ON data.CategoryID = Category.ID
AND data.Year = Dates.Year
AND data.Month = Dates.Month
WHERE data.Year BETWEEN #### and ####
AND data.Month BETWEEN # AND #
AND data.Property IN (‘A1’,’B1’)
AND data.Property2 IN (‘C1’,’D1’)
GROUP BY
Category.name,
Dates.Year,
Dates.Month
The only differences as far as can see are that I'm using a where clause on data, and have missed of the ORDER BY, which shouldn't make a difference. But I'm still having no joy.