简体   繁体   中英

SQL - creating date range

I am using the following follow script to show me the cap_date and max_capacity in the future and ... and sub-queries to show me the last_date and last_qty where older than the first select statement.

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)

Output from this script looks like ...

在此处输入图片说明

... what I would like is to do is create a date list starting from the 'last_date' and show a qty for each date equal to last_qty; once the date list reaches the 'cap_date' qty should change to the max_capacity (the dates should run 7 days after the 'cap_date', ie

在此处输入图片说明

Any ideas? Thanks

First create a cal table containing the range of dates of interest. Lets call that table cal with one column dt of type date. Assume your table above is called table_cap

Now do a

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM