合并表和统一日期
在 SQL 中,组合多个表的数据对于进行全面分析至关重要。此问题需要合并两个表(入站和出站),以跟踪产品移动。初始查询有效地合并了这些表,但有一个额外的要求,即唯一地显示日期。
使用 UNION ALL 和 GROUP BY 的唯一日期显示
实现唯一日期显示,原来的查询可以修改为使用UNION ALL与GROUP结合使用BY:
SELECT Date, Product, SUM(Inbound) as Inbound, SUM(Outbound) as Outbound FROM ((SELECT Inbound_Date As Date, Product, SUM(Quantity) as Inbound, 0 as Outbound FROM Inbound GROUP BY 1,2 ) UNION ALL (SELECT Outbound_Date, Product, 0 as Inbound, COUNT(*) as Outbound FROM Outbound GROUP BY 1,2 ) ) io GROUP BY Date, Product;
更改细分:
输出解释:
修改后的查询产生所需的输出:
Date | Product | Inbound | Outbound |
---|---|---|---|
2017-05-23 | Product A | 400 | 1 |
2017-09-04 | Product C | 380 | 0 |
2017-10-18 | Product C | 0 | 1 |
... | ... | ... | ... |
2018-09-10 | Product B | 200 | 1 |
... | ... | ... | ... |
以上是在 SQL 中合并入站和出站产品移动数据时如何显示唯一日期?的详细内容。更多信息请关注PHP中文网其他相关文章!