SQL - 创建日期范围

时间:2014-10-23 16:51:28

标签: sql

我正在使用以下脚本向我展示未来的cap_date和max_capacity以及...以及子查询,以显示last_date和last_qty,其中比第一个select语句更旧。

select 
    trunc(gp.cap_date) cap_date, gp.max_capacity, 
    (select max(trunc(gp1.cap_date)) 
     from GPS_CAPACITY gp1 
     where gp.plant = gp1.plant 
       and gp.work_center_no = gp1.work_center_no 
       and gp1.cap_date = (select max(gp2.cap_date) 
                           from GPS_CAPACITY gp2 
                           where gp.plant = gp2.plant 
                             and gp.work_center_no = gp2.work_center_no 
                             and gp2.cap_date < gp.cap_date)) last_date,
    (select max(gp1.max_capacity) 
     from GPS_CAPACITY gp1 
     where gp.plant = gp1.plant 
       and gp.work_center_no = gp1.work_center_no 
       and gp1.cap_date = (select max(gp2.cap_date) 
                           from GPS_CAPACITY gp2 
                           where gp.plant = gp2.plant 
                             and gp.work_center_no = gp2.work_center_no 
                             and gp2.cap_date < gp.cap_date)) last_qty
from 
    GPS_CAPACITY gp
where 
    gp.plant = 'W'
    and gp.work_center_no = 'HPKG'
    and trunc(gp.cap_date) > trunc(sysdate)

此脚本的输出看起来像......

enter image description here

...我想要做的是从'last_date'开始创建一个日期列表,并为每个等于last_qty的日期显示一个数量;一旦日期列表到达'cap_date',数量应改为max_capacity(日期应在'cap_date'后7天运行,即

enter image description here

有什么想法吗? 感谢

1 个答案:

答案 0 :(得分:0)

首先创建一个包含感兴趣日期范围的校准表。让我们用一个类型为date的列dt调用该表cal。假设您的上表名为table_cap

现在做一个

select cal.dt, case when cal.dt<cap_date then qty else max_capacity end 
from  cal
inner join table_cap on 
(table_cap.last_date <= cal.dt  
 and cal.dt < adddate(capdate, interval 7 day )