在一个SQL查询中合并两个表中的两列,并将表中的值用作列名

问题描述 投票:0回答:1

我有以下两个表,也可以在SQL fiddle here中找到:

CREATE TABLE Send_Orders (
    Send_Date DATE,
    Product TEXT,
    FlowType TEXT,
    Send_Quantity VARCHAR(255)
);

INSERT INTO Send_Orders
(Send_Date, Product, FlowType, Send_Quantity)
VALUES 
("2017-05-23", "Product A", "Send", "400"),
("2018-09-10", "Product B", "Send", "200"),
("2018-12-14", "Product B", "Send", "600"),
("2019-01-03", "Product A", "Send", "700"),
("2019-02-15", "Product C", "Send", "650"),
("2017-09-04", "Product C", "Send", "380"),
("2019-01-09", "Product A", "Send", "120"),
("2019-02-16", "Product A", "Send", "470"),
("2019-02-12", "Product A", "Send", "920"),
("2019-02-15", "Product C", "Send", "860"),
("2018-01-03", "Product B", "Send", "610");


CREATE TABLE Return_Orders (
    Return_Date DATE,
    Product TEXT,
    DeliveryType TEXT
);

INSERT INTO Return_Orders
(Return_Date, Product, DeliveryType)
VALUES 
("2017-06-24", "Product A", "Return"),
("2018-12-18", "Product B", "Return"),
("2018-12-18", "Product B", "Return"),
("2019-02-01", "Product A", "Return"),
("2019-02-22", "Product C", "Return"),
("2017-10-18", "Product C", "Return"),
("2019-04-12", "Product A", "Return"),
("2019-04-12", "Product A", "Return"),
("2019-04-12", "Product A", "Return"),
("2019-04-19", "Product C", "Return"),
("2018-05-17", "Product B", "Return");

我使用以下SQL合并两个表:

(SELECT Send_Date As Event_Date, Product, FlowType, 
       SUM(Send_Quantity) as Quantity
 FROM Send_Orders
 GROUP BY Send_Date, Product, FlowType
) 
UNION ALL
(SELECT Return_Date, Product, DeliveryType, COUNT("Product") 
 FROM Return_Orders
 GROUP BY Return_Date, Product, DeliveryType
)
ORDER BY 1,2;

所有这些都很好。


[现在,我想实现将FlowTypeDeliveryType中的值用作columnname。最后,查询结果应如下所示:

Event-Date      Product      Send_Quantity      Return_Quantity   
2017-05-23     Product A       400                NULL
2017-06-24     Product A       NULL               1      
2017-09-04     Product C       380                NULL
2017-10-18     Product C       NULL               1
:              :               :                  :
:              :               :                  :
:              :               :                  :

我需要在我的SQL代码中进行哪些更改才能使其正常工作?

mysql sql
1个回答
0
投票

使用union allgroup by

SELECT Event_date, Product, SUM(send_quantity), SUM(return_quantity)
FROM ((SELECT Send_Date As Event_Date, Product, FlowType, 
              SUM(Send_Quantity) as send_quantity,
              0 as return_quantity
       FROM Send_Orders
       GROUP BY Send_Date, Product, FlowType
      ) UNION ALL
      (SELECT Return_Date, Product, DeliveryType, 
              0 as send_quantity,
              COUNT(*) as return_quantity
       FROM Return_Orders
       GROUP BY Return_Date, Product, DeliveryType
      )
     ) sr
GROUP BY Event_date, Product;

您可以从子查询中删除FlowTypeDeliveryType。但是您的查询中有它们,因此由于某些原因它们可能有用。

© www.soinside.com 2019 - 2024. All rights reserved.