2

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.

4

3 回答 3

2

您需要将 Category 添加到您的Table2,或者(甚至更好)有一个Category表。

然后,您需要按这些查找表而不是数据表进行分组。

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
于 2012-10-31T11:50:19.287 回答
0

不要在语句中添加年份和月份,而是分别检查月份和年份的条件。像这样 ON Table2.Year = Table.Year 和 Table2.Month = Table.Month

于 2012-10-31T11:52:19.130 回答
0
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;
于 2012-10-31T11:45:46.260 回答