首先我们我T_ITL_SEAT_INFO表,有6条数据
同时T_IHIS_SEAT_CAPITAL表有4条数据,20190401~20190404每天只有一个f_seat_id的数据
我们现在的需求是,要求查出指定日期区间内T_ITL_SEAT_INFO中所有f_seat_id的f_self_amount的值,不存在则设为0。
解决方法:1.查询出已经存在的数据,2 按照笛卡尔积查询所有f_seat_id同时去除已经存在的数据。
sql如下:
with t_itl_seat_info1 as(
select
a.f_trade_date,
b.f_seat_id
from
T_ITL_SEAT_INFO b join(
select distinct t.f_seat_id, t.f_trade_date
from T_IHIS_SEAT_CAPITAL t
where 1=1
and t.f_trade_date >= '20190401'
and t.f_trade_date <= '20190404'
) a on b.f_seat_id = a.f_seat_id
union all
select
a.f_trade_date,
b.f_seat_id
from
T_ITL_SEAT_INFO b CROSS JOIN(
select distinct t.f_trade_date
from T_IHIS_SEAT_CAPITAL t
where 1=1
and t.f_trade_date >= '20190401'
and t.f_trade_date <= '20190404'
) a where not exists(
select 1 from T_IHIS_SEAT_CAPITAL t
where b.f_seat_id = t.f_seat_id
and a.f_trade_date = t.f_trade_date
and t.f_trade_date >= '20190401'
and t.f_trade_date <= '20190404'
)
)
select
b.f_trade_date,
b.f_seat_id,
nvl(a.f_self_amount, 0)
from t_itl_seat_info1 b
left join T_IHIS_SEAT_CAPITAL a
on b.f_seat_id = a.f_seat_id and b.f_trade_date = a.f_trade_date
order by b.f_trade_date
执行之后,我们可以看到有24条数据,成功!