在 SQL 中合并两个具有唯一日期值的表
在数据集成场景中,合并具有相似结构但可能存在数据重叠的表可能会导致挑战,特别是在处理重复值时。考虑以下两个表:
CREATE TABLE Inbound ( Inbound_Date DATE, Product TEXT, InboundType TEXT, Quantity VARCHAR(255) ); CREATE TABLE Outbound ( Outbound_Date DATE, Product TEXT, OutboundType TEXT );
使用传统的 UNION 查询,可以按如下方式合并这些表:
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("Outbound_Type") as Outbound FROM Outbound GROUP BY 1,2 ) ORDER BY 1,2;
但是,这种方法允许存在重复的日期。为了确保每个日期都是唯一的,我们可以修改查询以使用 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;
此查询首先执行 UNION ALL 操作来组合两个表中的行,创建一个集合具有重叠日期和产品的行。然后,它使用嵌套查询块来计算每个日期和产品组合的入库和出库数量之和。最后,应用 GROUP BY 子句来消除重复的日期值,确保每个日期在最终结果中只出现一次。
因此,修改后的查询会生成一个具有唯一日期的表,这很有用用于进一步分析或数据操作任务。
以上是如何合并两个具有重叠日期的 SQL 表并确保结果中的日期值唯一?的详细内容。更多信息请关注PHP中文网其他相关文章!