Oralce之补日期区间内的sql

本文介绍了如何使用Oracle SQL查询填补日期区间内缺失的数据。通过查询已存在记录并结合笛卡尔积,确保每个日期对应的所有f_seat_id都有f_self_amount值,不存在的数据填充为0。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先我们我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条数据,成功!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值