问题描述
我需要一些帮助。我希望能够计算 SQL 中边的净方向。数据如下所示:
Select *
from data
Source destination weight
A B 12
C B 5
D A 7
B A 6
F G 20
B C 2
G F 7
我希望最终结果如下所示:
Source destination weight
A B 6
C B 3
D A 7
F G 13
有没有一种简单的方法可以在 SQL 中编写它?
我使用的是 SQL Server。
解决方法
您可以使用 conditional aggregation
和 group by
最少,最多如下:
select IIF(source < destination,source,destination) as src,IIF(source > destination,destination) as dest
sum(case when source < destination then weight else -weight end) as weight
from your_Table
group by IIF(source < destination,destination),destination)