繁体   English   中英

在一个 SQL 查询中合并两个表中的两列并合并 COUNT 和 SUM 值

[英]Merge two columns from two tables in one SQL query and combine COUNT and SUM values

我有以下两个表,您也可以在此处SQL fiddle找到

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");

现在,我想运行一个查询并将Send_DateReturn_DateReturn_Date到一个名为Event_Date列中,因此结果应如下所示:

Event_Date      Product      FlowType   Quantity
2017-05-23       Product A    Send       400
2017-06-24       Product A    Return       1
2018-09-10       Product B    Send       200
2018-12-18       Product B    Return       2
:                :            :
:                :            :
:                :            :

我试图与解决方案去从这里,但它总结了quantity到一个日期,不会列出每个日期。

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

我需要在SQL更改什么才能合并列并列出每个日期?

你需要GROUP BY 我认为:

(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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM