[英]How to sum columns from two tables if the month match and group by month
目前,我已经实现了使用此查询的单个表来做到这一点:
SELECT EXTRACT(MONTH FROM date) as month, SUM(total) as total FROM invoices GROUP BY month ORDER BY month ASC
但是现在我很疯狂,试图从两列中返回相同的结果,比如total1和total2,并按月分组,如果其中一个列中一个月内没有发票,则结果应该为0。
表结构和预期结果:
invoices payments
date date
total income
month totalInvoices totalPayments
1 10005 8017
2 756335 5019
3 541005 8017
4 34243 8870
我该如何实现? 有什么建议么?
您需要查询结构的第三个元素,该元素提供所有相关年/月的完整列表。 这可能是现有的表或子查询,但是整个查询将遵循以下概述的结构:
CREATE TABLE invoices (`id` int, `invdate` datetime, `invtotal` numeric);
INSERT INTO invoices (`id`, `invdate`, `invtotal`) VALUES (1, '2017-01-21 00:00:00', 12.45);
CREATE TABLE payments (`id` int, `paydate` datetime, `paytotal` numeric);
INSERT INTO payments (`id`, `paydate`, `paytotal`) VALUES (1, '2017-02-21 00:00:00', 12.45);
select ym.year, ym.month, inv.invtotal, pay.paytotal from ( SELECT EXTRACT(YEAR FROM invdate) as year , EXTRACT(MONTH FROM invdate) as month FROM invoices UNION SELECT EXTRACT(YEAR FROM paydate) as year , EXTRACT(MONTH FROM paydate) as month FROM payments ) ym left join ( SELECT EXTRACT(YEAR FROM invdate) as year , EXTRACT(MONTH FROM invdate) as month , SUM(invtotal) as invtotal FROM invoices GROUP BY year, month ) inv on ym.year = inv.year and ym.month = inv.month left join ( SELECT EXTRACT(YEAR FROM paydate) as year , EXTRACT(MONTH FROM paydate) as month , SUM(paytotal) as paytotal FROM payments GROUP BY year, month ) pay on ym.year = pay.year and ym.month = pay.month;
\n 年| 一个月 合计 支付总额\n ----- | ------- | ---------- | -------- |\n 2017 | 1 | 12 | 空 |\n 2017 | 2 | 空 | 12 |\n
在我的示例中,“第三个元素”是子查询ym,但这对于您的实际查询而言可能效率太低,但是它应该帮助服务器确定如何在不同的时间范围内协调数据。
dbfiddle 在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.