各个大神,项目期间遇到一个问题,需求如下
表中有两列,其中第一列的中数据在第二列存在,第二列的数据在第一列中存在,相互存在的需要合并成同一条记录,请教如何实现,
表数据如下
A  B
1  2
2  1
1  3
3  4
4  3现在要查询出来的结果
A  B
1  2
1  3
3  4

解决方案 »

  1.   


    SQL> 
    SQL> create table test(a int, b int);
    Table created
    SQL> begin
      2      insert into test values(1, 2);
      3      insert into test values(2, 1);
      4      insert into test values(1, 3);
      5      insert into test values(3, 4);
      6      insert into test values(4, 3);
      7  end;
      8  /
    PL/SQL procedure successfully completed
    SQL> select distinct least(a, b) a, greatest(a,b) b
      2  from test;
             A          B
    ---------- ----------
             1          2
             1          3
             3          4
    SQL> drop table test purge;
    Table droppedSQL> 
      

  2.   

    方法不错
    假如加入
    insert into test values(8, 6);
    这条记录,是不是展示时有点问题
      

  3.   

    select t1.* 
    from test t1,test t2
    where t1.a=t2.b and t1.b=t2.a and t1.a<t1.b
    union
    select * from test t where (t.a,t.b) not in
    (select t1.* 
    from test t1,test t2
    where t1.a=t2.b and t1.b=t2.a);
      

  4.   


    嗯,a,b 的显示前后顺序会变。 不知道会不会对楼主的实际需求有没有影响;
    ----------------------------------------------------------------------
    确实会有这种情况,然后可能刚才没有描述清楚,A和B列都是些字符串。
      

  5.   

    方法不错
    假如加入
    insert into test values(8, 6);
    这条记录,是不是展示时有点问题delete from tt 
    where a  in (
                   select t2.a
                   from tt t1,tt t2
                   where t1.a = t2.b and t2.a = t1.b and t2.a > t2.b
                   )
    这样就没问题了
      

  6.   

    select * from tb a,tb b
    where a.列1=b.列2 and a.列2=b.列1
    如果你要显示的是必须相同的话
      

  7.   

    select  a,b from table 
    union 
    select b,a from table
      

  8.   

    select t1.* 
    from test t1,test t2
    where t1.a=t2.b and t1.b=t2.a and t1.a<t1.b
    union
    select * from test t where (t.a,t.b) not in
    (select t1.* 
    from test t1,test t2
    where t1.a=t2.b and t1.b=t2.a);
      

  9.   

    学到了least和greatest
      

  10.   

    select * from table where a<b;