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

时间:2017-04-13 18:54:28

标签: sql postgresql

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

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

如何使用查询完成此操作?

4 个答案:

答案 0 :(得分:3)

使用left join自动将表连接到反向位置并返回c1小于c2的表,或者没有匹配的行。当左侧加入coalesce0时,使用count添加null

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 |
+----+----+-------+

答案 1 :(得分: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,因此如果任一值为{{1},您可能需要小心}}

答案 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;

答案 3 :(得分:0)

也许用相同的c2,c1?

连接输出c1,c2
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