2017-04-13 34 views
2

联接同桌后,我有这样的结果:SQL增加值的行,如果列被切换

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 

这怎么能通过查询来完成?

+0

用您正在使用的数据库标记您的问题。 –

回答

1

许多数据库支持least()greatest()。如果它们是可用的,你可以这样做:

select least(c1, c2) as c1, greatest(c1, c2) as c2, sum(count) as cnt 
from (<your query here>) t 
group by least(c1, c2), greatest(c1, c2); 

在不支持这些功能的数据库,你可以使用case

注:least()greatest()回报NULL语义如果任一列NULL,所以你可能需要小心,如果任一值可以是NULL

3

使用left join自动加入反向位置的表格,并返回c1小于c2或者它没有匹配的行。使用​​3210加入0时,左侧加入countnull

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 

rextester演示在SQL Server:http://rextester.com/VBQI62112

回报:

+----+----+-------+ 
| c1 | c2 | count | 
+----+----+-------+ 
| A | B |  7 | 
| A | C |  5 | 
| B | C |  2 | 
+----+----+-------+ 
0
SELECT t.c1 
     , t.c2 
     , t.cnt + CASE WHEN s.cnt IS NULL THEN 0 ELSE s.cnt END as cnt 
    FROM t 
    LEFT JOIN 
     t as s 
    ON t.c1 = s.c2 
    AND t.c2 = s.c1 
WHERE t.c1 < t.c2; 
0

或许加盟输出C1,C2与同C2,C1?

select t1.c1 
     ,t1.c2 
     ,sum(coalesce(t1.count,0), coalesce(t2.count,0)) 
from table t1 
left join table t2 
    on t1.c1 = t2.c2 
    and t1.c2 = t2.c1 
group by t1.c1, t1.c2 
having t1.c1 < t1.c2