已有数据
A     B     C     D
----------------------
a1    a2    a     1
a1    a3    a     3
a2    a1    a     6...想得到的结果,A到B的值D放在D1,在C相同的情况下,对应B到A的值D放在D2,没有填0,行数不定
A     B     C     D1   D2
-------------------------    
a1    a2    a     1    6
a1    a3    a     3    0
...请教高手写个sql,先谢谢了!

解决方案 »

  1.   


    在加几条数据看看,就是把一些反过来的数据放在同一行
    A   B   C   D
    ----------------------
    a1 a2 a 1
    a1 a3 a 3
    a2 a1 a 6
    a2 a3 b 12
    a3 a2 b 23
    a3 a2 c 44 
    ...A  B  C  D1  D2
    -------------------------   
    a1 a2 a 1 6
    a1 a3 a 3 0
    a2 a3 b 12 23
    a3 a2 c 44 0
    ...
      

  2.   


    --没测试过,你试试:
    select t1.a,t1.b,t1.c,t1.d,nvl(t2.d,0)
    from tab t1 left join ab t2 on t1.b=t2.a and t1.a=t2.b;
      

  3.   


    --再试试:
    select t1.a,t1.b,t1.c,t1.d,t2.d
    from tab t1 ,tab t2 where  t1.b=t2.a and t1.a=t2.b
    union 
    select a,b,c,d,0 
    from tab t1 where not exists(select 1 from tab t2 where  t1.b=t2.a and t1.a=t2.b)
      

  4.   


    先谢谢你的回复,不过还是有重复问题
    a1 a2 a 1 6
    a2 a1 a 6 1
    是这种重复, 能否取一条
      

  5.   

    数据是对称的.a1到a2和a2到a1怎么区分?
      

  6.   


    A到B的值是D1,B到A的值是D2
    我现在写出来的是这种情况
    a1 a2 a 1 6
    a2 a1 a 6 1
    有一条是冗余的,取任意一条即可表达意思
      

  7.   

    SQL> select * from tbl_con;
     
    A          B          C          D
    ---------- ---------- ---------- ----------
    a1         a2         a          1
    a1         a3         a          3
    a2         a1         a          6
     
    SQL> 
    SQL> select * from (select a.a,a.b,a.c,a.d d1,b.d d2,row_number()over(partition by case when a.a>a.b then a.b||a.a||a.c else a.a||a.b||a.c end order by a.d) rn
      2                   from tbl_con a left join tbl_con b on a.c=b.c and a.a=b.b and b.a=a.b)
      3   where rn=1
      4  ;
     
    A          B          C          D1         D2                 RN
    ---------- ---------- ---------- ---------- ---------- ----------
    a1         a2         a          1          6                   1
    a1         a3         a          3                              1
     
    SQL> 
      

  8.   

    partition by case when a.a>a.b then a.b||a.a||a.c else a.a||a.b||a.c end 
    这里为了保险起见,你可以在字段中间拼上一个肯定不会再字段中出现的字符,来保证数据不会出现问题.