【问题标题】: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;

那我该怎么办?

【问题讨论】:

    标签: mysql sql join merge outer-join


    【解决方案1】:

    您可以使用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;
    

    【讨论】:

    • 谢谢!它可以工作并提供预期的输出
    猜你喜欢
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2015-02-20
    • 1970-01-01
    相关资源
    最近更新 更多