合併表和統一日期
在 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中文網其他相關文章!