如果月份匹配和按月分组,如何对两个表中的列进行求和

时间:2017-06-16 20:13:47

标签: mysql

目前,我已经实现了使用此查询的单个表:

SELECT EXTRACT(MONTH FROM date) as month, SUM(total) as total FROM invoices         GROUP BY month ORDER BY month ASC

但是现在我疯狂地试图从两列中返回相同的结果,如果其中一列中的一个月内没有发票,那么就说出total1和total2,以及逐月结果应该是cero。

表格结构和预期结果:

invoices payments
date     date
total    income


month      totalInvoices   totalPayments    
1         10005            8017  
2         756335           5019  
3         541005           8017  
4         34243            8870 

我如何实现这一目标?有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您需要查询结构的第三个元素,它提供所有相关年/月的完整列表。这可能是现有表或子查询,但整体查询将遵循下面概述的结构:

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;
year | month | invtotal | paytotal
-----|-------|----------|--------|
2017 |     1 |       12 |   null |
2017 |     2 |     null |     12 |

在我的示例中,“第三个元素”是子查询 ym ,但这可能对您的实际查询来说效率太低,但它应该服务器来识别如何在不同的时间范围内协调数据。

dbfiddle here