Mysql 要转置的Sql查询(排序)

Mysql 要转置的Sql查询(排序),mysql,sql,Mysql,Sql,我有一张桌子,看起来像: Product Source_Store Destination_Store Quantity A Store1 Store2 4 B Store3 Store4 3 C Store2 Store3 1 我

我有一张桌子,看起来像:

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来实现这一点吗?可以使用case when语句吗? 请帮忙。
提前感谢。

当然,最简单的方法是使用两个insert查询:

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);
这似乎有效:

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

您可以使用简单的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