1

我有以下两个记录支出并提供支出类别信息的表:

表事务:

+-------+--------+--------+
| month | cat_id | amount |
+-------+--------+--------+
|     1 |      2 |      3 |
|     1 |      2 |      8 |
|     2 |      1 |      7 |
|     2 |      1 |      5 |
+-------+--------+--------+

表类别:

+--------+-------------+
| cat_id | cat_desc    |
+--------+-------------+
|      1 | Stock       |
|      2 | Consumables |
+--------+-------------+

我想要的是构建一个查询,显示每个类别每个月的金额总和,即使该类别在该月没有支出,如下所示:

+-------+-------------+--------+
| month | cat_desc    | amount |
+-------+-------------+--------+
|     1 | Stock       |      0 |
|     1 | Consumables |     11 |
|     2 | Stock       |     12 |
|     2 | Consumables |      0 |
+-------+-------------+--------+

我怀疑需要使用外部联接,但我还没有找到执行此操作的语句。

感谢您的任何帮助。

4

3 回答 3

2

这应该为您提供正确的结果。内部选择准备了一个包含所有类别的所有月份的列表,LEFT JOIN其余的处理。

SELECT t.month, t.cat_desc, COALESCE(SUM(t2.amount), 0) amount
FROM (
  SELECT DISTINCT t.month, c.cat_id, c.cat_desc
  FROM categories c
  CROSS JOIN transactions t
) t
LEFT JOIN transactions t2 ON ( t2.month = t.month AND t2.cat_id = t.cat_id )
GROUP BY t.month, t.cat_desc

以下内容可能会更好(DISTINCT仅在必要时使用),但您必须尝试:

SELECT t.month, t.cat_desc, COALESCE(SUM(t2.amount), 0) amount FROM (
  SELECT t.month, c.cat_id, c.cat_desc
  FROM
  (SELECT DISTINCT month FROM transactions) t
  CROSS JOIN categories c
) t
LEFT JOIN transactions t2 ON ( t2.month = t.month AND t2.cat_id = t.cat_id )
GROUP BY t.month, t.cat_desc
于 2010-02-12T22:48:43.810 回答
0
SELECT c.cat_id, c.cat_desc,t.month, SUM(t.amount) 
FROM categories c 
LEFT JOIN transactions t ON (t.cat_id = c.cat_id)
GROUP BY c.cat_id,t.month
于 2010-02-12T22:32:24.563 回答
0
SELECT c.cat_id, c.cat_desc,t.month, SUM(t.amount)  
FROM categories c  
LEFT JOIN transactions t ON (t.cat_id = c.cat_id) 
GROUP BY t.month,c.cat_id 
Order By t.month
于 2010-02-12T22:57:02.010 回答