gpt4 book ai didi

mysql - 要转置的 SQL 查询(某种程度上)

转载 作者:行者123 更新时间:2023-11-29 06:22:37 28 4
gpt4 key购买 nike

我有一张看起来像这样的表:

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 语句?请帮忙。提前致谢。

最佳答案

这似乎可行:

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

关于mysql - 要转置的 SQL 查询(某种程度上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32654808/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com