gpt4 book ai didi

SQL 添加行的值,如果列被切换

转载 作者:行者123 更新时间:2023-11-29 11:58:54 24 4
gpt4 key购买 nike

在同一个表的连接之后,我有这样的结果:

c1   c2  count
A B 5
A C 4
B A 2
B C 2
C A 1

现在,如果 c1c2 互换,数字应该相加,如下所示:

c1   c2  count
A B 7
A C 5
B C 2

这如何通过查询完成?

最佳答案

使用 left join 在反向位置上自连接表并返回 c1 小于 c2 的表,或者它没有匹配行。当左连接的countnull 时,使用coalesce 添加0

select 
t.c1
, t.c2
, t.count + coalesce(s.count,0) as count
from t
left join t as s
on t.c1 = s.c2
and t.c2 = s.c1
where t.c1 < t.c2 or s.c1 is null

sql server 中的 rextester 演示:http://rextester.com/VBQI62112

返回:

+----+----+-------+
| c1 | c2 | count |
+----+----+-------+
| A | B | 7 |
| A | C | 5 |
| B | C | 2 |
+----+----+-------+

关于SQL 添加行的值,如果列被切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43399744/

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