我想显示表A中与表B中的日期匹配的所有日期。 如果表A中没有表A日期,则应选择以前可用的日期。
例如,
我有表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"
有人可以帮帮我吗?
答案 0 :(得分: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;