SQL Server,在不同的列中查找交叉值

时间:2018-12-19 03:50:31

标签: sql sql-server multiple-columns sql-server-2017

我需要帮助进行sql服务器查询。我必须有很多这样的行,并且我的表有3列,例如a,b,c。

      a          b          c
     ---        ---        ---
    hello      world       10
     hey        you        80
    world      hello       20
     my         day        15
    merhaba    dunya       40
    bugun      nasilsin    75
    dunya      merhaba     20

因此,我想添加c列值来查找不同列中的交叉值。所以查询后我想看看;

      a          b          c
     ---        ---        ---
    hello      world       30
     hey        you        80
      my        day        15
    merhaba    dunya       60
     bugun     nasilsin    75

对不起,我的英语不好,谢谢您的回答...

编辑:答案不起作用。我都试过了。您对这个解决方案人员有任何想法吗?

2 个答案:

答案 0 :(得分:2)

这是一种实现方法

create table t(a varchar(10), b varchar(10), c varchar(10))

insert into t values('hello','world',10)
insert into t values('world','hello',20)

select  min(a) as a
       ,max(b) as b
       ,sum(cast(c as int)) as c
  from t as x
 group by case when a>b then a
            else b
       end

答案 1 :(得分:0)

如果存在不匹配的行或“成对”,则:

CREATE TABLE mytable(
   a      VARCHAR(50) NOT NULL
  ,b      VARCHAR(50) NOT NULL
  ,c      INTEGER  NOT NULL
);
INSERT INTO mytable(a,b,c) VALUES ('hello','world',10);
INSERT INTO mytable(a,b,c) VALUES ('hey','you',80);
INSERT INTO mytable(a,b,c) VALUES ('world','hello',20);
INSERT INTO mytable(a,b,c) VALUES ('my','day',15);
INSERT INTO mytable(a,b,c) VALUES ('merhaba','dunya',40);
INSERT INTO mytable(a,b,c) VALUES ('bugun','nasilsin',75);
INSERT INTO mytable(a,b,c) VALUES ('dunya','merhaba',20);


GO
7 rows affected
select t.a, t.b, sum(t.c + coalesce(t2.c,0))
from mytable t
left join mytable t2 on t.a = t2.b and t.b = t2.a
group by  t.a, t.b


GO
a       | b        | (No column name)
:------ | :------- | ---------------:
my      | day      |               15
merhaba | dunya    |               60
world   | hello    |               30
dunya   | merhaba  |               60
bugun   | nasilsin |               75
hello   | world    |               30
hey     | you      |               80

db <>提琴here