2017-05-10 53 views
0

前一個可用的價值我想顯示從表A,其與從表B.日期匹配的所有日期 如果表A日期不在表B提供,那麼它應該選擇以前可用的日期。如果表中的值是不可用表B中,然後選擇從表B中

例如,

我有表A作爲

Date1 
"2017-04-10" 
"2017-04-11" 
"2017-04-12" 
"2017-04-13" 
"2017-04-14" 
"2017-04-15" 
"2017-04-16" 
"2017-04-17" 
"2017-04-18" 
"2017-04-19" 
"2017-04-20" 

和表B中

Date2 
"2017-04-10" 
"2017-04-11" 
"2017-04-12" 
"2017-04-13" 
"2017-04-18" 
"2017-04-19" 
"2017-04-20" 

結果我看到的是,

Date1  | NewDate 
"2017-04-10" | "2017-04-10" 
"2017-04-11" | "2017-04-11" 
"2017-04-12" | "2017-04-12" 
"2017-04-13" | "2017-04-13" 
"2017-04-14" | "2017-04-13" 
"2017-04-15" | "2017-04-13" 
"2017-04-16" | "2017-04-13" 
"2017-04-17" | "2017-04-13" 
"2017-04-18" | "2017-04-18" 
"2017-04-19" | "2017-04-19" 
"2017-04-20" | "2017-04-20" 

燦有人請幫助我?

回答

2

一種方法是使用一個橫向連接或相關子查詢:

select a.*, 
     (select b.date 
     from b 
     where b.date <= a.date 
     order by b.date desc 
     limit 1 
     ) b 
from a; 

如果有大量的數據,那麼下面會更有效:

select a.date, b_date 
from (select a.date, 
      max(b_date) over (order by date, b_date) as b_date 
     from ((select a.date as date, null as b_date 
      from a 
      ) union all 
      (select b.date as date, b.date as b_date 
      from b 
      ) b 
      ) ab 
    ) ab 
where b_date is not null; 
相關問題