日期:2014-05-17  浏览次数:20753 次

【oracle】相当虔诚求教!查询表中每天的余额,如果当天没有就返回之前最近的一天的余额。
本帖最后由 KittyPray 于 2012-11-15 16:00:35 编辑
 
需求:
【oracle】查询表中每天的余额,如果当天没有就返回之前最近的一天的余额。
场景:
a 表每天抽取并计算话费余额(只抽取正常开机的),一个号码每天一条记录,记录该号码每天的余额。
如果一个号码123在9.12号申请停机了,于是a表便不再有123号码9.12号之后的记录。
此时查询123号码9.13时之后的余额应该还是9.12的余额。
问题:
求大神给个脚本(只要能查出来就行,function,procedure,sql都行)查询9.10-9.15号123的余额能返回如下结果:
a表字段 id,number,time,balance

id     time                balance
6      2012.9.15           98.2
5      2012.9.14           98.2
4      2012.9.13           98.2
3      2012.9.12           98.2
2      2012.9.11           102.8
1      2012.8.10           110.5

------解决方案--------------------
麻烦点的

with t1 as
(
     select 1 id,date'2012-11-08' time,'100' balance from dual
     union all
     select 2 id,date'2012-11-10' time,'80' balance from dual
     union all
     select 3 id,date'2012-11-11' time,'70' balance from dual
)

select t.t_date,nvl(balance,(select balance from t1 where time = (select max(time) from t1 where time <= t_date))) balance
from 
(
     select m_date+level-1 t_date
     from (select min(time) m_date from t1)
     connect by level <= to_date('2012-11-15','yyyy-mm-dd')-m_date+1
) t left join t1 on t_date = time
order by t_date

      t_date     balance
----------------------------------
1 2012/11/8 100
2 2012/11/9 100
3 2012/11/10 80
4 2012/11/11 70
5 2012/11/12 70
6 2012/11/13 70
7 2012/11/14 70
8 2012/11/15 70


------解决方案--------------------
可以将里面的2个日期都设为参数 来构造一个日期表  连接当前表 关联得到信息  为空的赋值当前日期前最后一个日期的金额