如何将每月销售额和每月购买 table 合并为一个 table?

How can I merge Monthly Sales and Monthly Purchase table into one singe table?

我有两个 table:月销售额(月,total_sales)和月采购(月,total_purchase)。我需要结合 table 和输出 (month, total_sales, total_purchase).

Month_Sales:       Monthly_Purchase:
+----+----------+  +-----+-------------+
| Month | sales |  |  Month | purchase |
+----+----------+  +-----+-------------+
| Jan  | 50000  |  | Jan    | 50000    |
| Mar  | 20000  |  | Feb    | 60000    |
| Jun  | 10000  |  | Mar    | 40000    |
+----+----------+  +-----+-------------+

输出:

+----+----------+---------+
| Month | sales | purchase|
+----+----------+---------+
| Jan  | 50000  | 50000   |
| Feb  |  NULL  | 60000   |
| Mar  | 20000  | 40000   |
| Jun  | 10000  | NULL    |
+----+----------+---------+

我尝试使用 FULL OUTER JOIN 实现此目的,但它没有提供预期的结果。

SELECT Table1.month, Table1.sales, Table2.purchase FROM (SELECT month, sales from Monthly_Sales) as Table1
FULL OUTER JOIN (SELECT month, purchase from Monthly_Purchase) as Table2
ON Table1.month = Table2.month;

那我该怎么办?

您可以使用 union allgroup by:

select month, sum(sales), sum(purchase)
from ((select month, sales, null as purchase
       from sales
      ) union all
      (select month, null, purchase
       from purchases
      )
     ) sp
group by month;