Paul Flowerdew
Paul Flowerdew

Reputation: 73

SQL query to display aggregated data when result is zero

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.

Upvotes: 2

Views: 771

Answers (3)

MatBailie
MatBailie

Reputation: 86706

You need to add Category to your Table2, or (even better) have a Category table.

Then, you need to group by those lookup tables, not the data table.

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
    AND data.Property  IN ('A1','B1') 
    AND data.Property2 IN ('C1','D1')
WHERE Dates.Year  BETWEEN #### AND ####
  AND Dates.Month BETWEEN #### AND ####
GROUP BY
  Category.name,
  Dates.Year,
  Dates.Month
ORDER BY
  Category.name,
  Dates.Year,
  Dates.Month

Upvotes: 2

Vikram Jain
Vikram Jain

Reputation: 5588

SELECT Table.Category, Table.Year, Table.Month, SUM(Table.Value) 
FROM Table
right outer  JOIN Table2
ON Table2.Year= Table.Year and Table2.Month =Table.Month
GROUP BY Table.Category,Table2.Year, Table2.Month;

Upvotes: 0

Pavi
Pavi

Reputation: 345

Instead of adding adding year and month in on statement, check the condition separately for month and year. like this ON Table2.Year = Table.Year and Table2.Month = Table.Month

Upvotes: 0

Related Questions