我有一张表格如下:
Product Source_Store Destination_Store Quantity
A Store1 Store2 4
B Store3 Store4 3
C Store2 Store3 1
我想从中生成一个表格,如下所示:
Store Product Quantity
Store1 A -4
Store2 A 4
Store3 B -3
Store4 B 3
Store2 C -1
Store3 C 1
我可以使用纯sql做到这一点吗?声明可能是通过使用案例? 请帮忙。 提前谢谢。
答案 0 :(得分:1)
这似乎有效:
SELECT Store = Source_Store, Product, Quantity = -1*SUM(Quantity)
FROM
(
SELECT Product = 'A', Source_Store = 'Store1', Destination_Store = 'Store2', Quantity = 4
UNION ALL
SELECT 'B','Store3','Store4',3
UNION ALL
SELECT 'C','Store2','Store3',1
) t
GROUP BY Source_Store, Product
UNION
SELECT Store = Destination_Store, Product, Quantity = SUM(Quantity)
FROM
(
SELECT Product = 'A', Source_Store = 'Store1', Destination_Store = 'Store2', Quantity = 4
UNION ALL
SELECT 'B','Store3','Store4',3
UNION ALL
SELECT 'C','Store2','Store3',1
) t
GROUP BY Destination_Store, Product
答案 1 :(得分:1)
您可以使用简单的SQL来完成。只需以这种方式从表中选择数据两次 -
SELECT store, Product, Quantity FROM (
SELECT product, Source_Store AS store, quantity * -1 AS Quantity FROM d
UNION
SELECT product, destination_store, Quantity FROM d) t
ORDER BY Product, store
答案 2 :(得分:0)
当然,最简单的方法是使用两个插入查询:
INSERT INTO table2 (Store, Product, Quantitiy) VALUES (SELECT Source_Store, Product, Quantity from table1);
INSERT INTO table2 (Store, Product, Quantitiy) VALUES (SELECT Destination_Store, Product, Quantity*-1 from table1);