MYSQL:当不存在值时返回零,每月分类
我有以下两个表,用于记录支出并提供支出类别信息:
表交易:
+-------+--------+--------+
| 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 |
+-------+-------------+--------+
我怀疑需要使用外部联接,但我还没有找到执行此操作的声明。
感谢您的帮助。
I have the following two tables that record expenditure and provide expenditure category information:
Table transactions:
+-------+--------+--------+
| month | cat_id | amount |
+-------+--------+--------+
| 1 | 2 | 3 |
| 1 | 2 | 8 |
| 2 | 1 | 7 |
| 2 | 1 | 5 |
+-------+--------+--------+
Table categories:
+--------+-------------+
| cat_id | cat_desc |
+--------+-------------+
| 1 | Stock |
| 2 | Consumables |
+--------+-------------+
What I would like is to construct a query that displays a sum of the amounts for each category, for each month, even if there is no expenditure in that category for that month like this:
+-------+-------------+--------+
| month | cat_desc | amount |
+-------+-------------+--------+
| 1 | Stock | 0 |
| 1 | Consumables | 11 |
| 2 | Stock | 12 |
| 2 | Consumables | 0 |
+-------+-------------+--------+
I suspect an outer join would need to be used but I haven't found a statement to do it yet.
Thank you for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该为您提供正确的结果。内部选择准备了所有月份与所有类别的列表,
LEFT JOIN
处理其余部分。使用以下方法可能会获得更好的性能(仅在必要时使用
DISTINCT
),但您必须尝试:This one should provide you with the correct result. The inner select prepares a list of all months combined with all categories, and the
LEFT JOIN
handles the rest.Performance might be better with the following (using
DISTINCT
only where necessary), but you will have to try: