如何将月销售和月采购表合并到一个表中?
Posted
技术标签:
【中文标题】如何将月销售和月采购表合并到一个表中?【英文标题】:How can I merge Monthly Sales and Monthly Purchase table into one singe table? 【发布时间】:2021-09-02 13:10:56 【问题描述】:我有两个表:月销售额(月,总销售额)和月采购(月,总采购)。我需要将表格和输出(月份、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;
那我该怎么办?
【问题讨论】:
【参考方案1】:您可以使用union all
和group 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;
【讨论】:
谢谢!它可以工作并提供预期的输出以上是关于如何将月销售和月采购表合并到一个表中?的主要内容,如果未能解决你的问题,请参考以下文章
在excel中如何将第一个工作表中的数据求和汇总到另一个表中