加入具有相似日期的行

时间:2014-02-11 12:33:24

标签: sql oracle join

我无法加入此查询。 这是我做了什么以及我希望做什么的一个例子(当然,期望的结果不是我得到的)。

  • 14-02-31 02实际为to_char(a_date,'YY-MM-DD hh24')

    --describe are the same
    sql> desc tab1
    
     Name              Null?    Type
     ----------------- -------- --------------------------------------------------------
     a_date                       DATE
     NAME                       VARCHAR2(20)
    
    select * from tab1;
    a_date          number
    -----           -------
    14-02-31 03     12
    14-02-31 04     22
    14-02-31 05     32
    14-02-31 06     42
    
    select * from tab2;
    a_date          number
    -----           -------
    14-02-31 02     21
    14-02-31 03     22
    14-02-31 06     23
    14-02-31 07     24
    
    select * from tab3;
    a_date          number
    -----           -------
    14-02-31 01     121
    14-02-31 03     222
    14-02-31 05     323
    14-02-31 07     424
    
    
    select a_date,t1.number,t2.number,t3.number
    from (select * from tab1) t1,
         (select * from tab2) t2,
         (select * from tab3) t3
    where t1.a_date=t2.a_date or
          t1.a_date=t3.a_date or
          t2.a_date=t3.a_date or
          t1.a_date is null or
          t2.a_date is null
    

    期望的结果:

    a_date          t1.number     t2.number     t3.number       
    -----           -------         -------         -------
    14-02-31 01                                     121
    14-02-31 02                     21
    14-02-31 03     12              22              222
    14-02-31 04     22
    14-02-31 05     32                              323
    14-02-31 06     42              23
    14-02-31 07                     24              424
    

2 个答案:

答案 0 :(得分:2)

我想你想要一个full outer join

select coalesce(t1.a_date, t2.a_date, t3.a_date) as a_date, t1.number, t2.number, t3.number
from tab1 t1 full outer join
     tab2 t2
     on t2.a_date = t1.a_date full outer join
     tab3 t3
     on t3.a_date = coalesce(t1.a_date, t2.a_date);

答案 1 :(得分:0)

select t1.a_date,t1.number,t2.number,t3.number
from  tab1 t1 left outer join on t1.a_date=t2.a_date
     tab2 t2 left outer join  on t1.a_date=t3.a_date
     tab3 t3  left outer join  on t2.a_date=t3.a_date
where t1.a_date=t2.a_date or
      t1.a_date=t3.a_date or
      t2.a_date=t3.a_date or
      t1.a_date is null or
      t2.a_date is null