Oracle自动补全日期,空数据为0

1.问题描述

   在数据库查询中计算年月周日的数据时候,会发现日期并不完整,希望日期可以自动补全,并且没有数据的字段补0

   最开始的数据展现为如下图

select nvl(sum(synnum),0)  value ,to_char(syntime, 'yyyy-MM-dd') lable from synlog where syntype in (4, 5,6) and trunc(syntime) > trunc(sysdate) -  30 group by  to_char(syntime, 'yyyy-MM-dd') order by 2; 
   最近30天数据查询出来只有2条数据,这并不是我想要得到的

  

2.具体实现  

   思路为:需要有一个最近30天的日期表,然后进行一个左关联,值为空即补0

     最近一月日期表     

select calendar_day
  from (select to_date((select to_char(sysdate , 'yyyy') from dual) || '0101',  'yyyymmdd') + level-1  as calendar_day from dual
   connect by level <to_char(to_date((select to_char(sysdate, 'yyyy') from dual) || '1231', 'yyyymmdd'), 'ddd'))
where calendar_day>= trunc(sysdate) - 29 and calendar_day<trunc(sysdate)+1

3.最终实现

   

select  a.calendar_day,
            nvl(b.value,0) as value from
(select calendar_day
  from (select to_date((select to_char(sysdate+1 , 'yyyy') from dual) || '0101',  'yyyymmdd') + level - 2 as calendar_day from dual
   connect by level <=to_char(to_date((select to_char(sysdate+1, 'yyyy') from dual) || '1231', 'yyyymmdd'), 'ddd'))
where calendar_day>= trunc(sysdate) -  29 and calendar_day<trunc(sysdate)+1) a
left join 
(select nvl(sum(synnum),0)  value ,
to_date( to_char(syntime, 'yyyymmdd'), 'yyyymmdd') lable from 
synlog where syntype in (4, 5, 6) and trunc(syntime) > trunc(sysdate) - 29 group by  to_date( to_char(syntime, 'yyyymmdd'), 'yyyymmdd')  )b
on a.calendar_day = b.lable order by a.calendar_day

   效果图:

   

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

让程序飞

您的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值