我有以下两张表记录支出并提供支出类别信息:
表格交易:
+-------+--------+--------+
| 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 |
+-------+-------------+--------+
我怀疑需要使用外部联接,但我还没有找到要做的声明。
感谢您的帮助。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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