gpt4 book ai didi

SQL 选择不同的列值到一行

转载 作者:行者123 更新时间:2023-12-04 18:28:44 26 4
gpt4 key购买 nike

我有一个表,其中的值是这样的:

StoreID | ItemID | OpeningClosingBalance | Total
1 | 1 | O | 10
1 | 1 | C | 20
1 | 2 | O | 5
1 | 2 | C | 7

第一行是特定项目的期初余额 10。第二行是同一项目的期末余额 20。第 3 行正在打开另一个项目,然后是结余余额等。我想要一个结果显示如下的查询:

StoreID | ItemID | Openingbalance | ClosingBalance
1 | 1 | 10 | 20
1 | 2 | 5 | 7

有人可以帮忙吗?

最佳答案

您可以使用条件聚合来做到这一点:

select StoreId, ItemId,
max(case when OpeningClosingBalance = 'O' then total end) as openingbalance,
max(case when OpeningClosingBalance = 'C' then total end) as closingbalance
from t
group by StoreId, ItemId;

关于SQL 选择不同的列值到一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42158714/

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