Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

SQL Query a MAX and MIN date from a Date Passed in

User_4DBINJan 31 2020 — edited Jan 31 2020
Mytable.datecaldates.current_period_stdCaldates.next_period_stdHeader 4
30/01/202001/01/202031/01/2020
14/02/202002/02/202026/02/2020

I have a table from which i query a dates : select date1 from mytable

For each one of these dates I want to determine a current_date_period and next_date_Period from another table that is a calendar table that contains 4 weekly period dates in rows.

I can do this in separate statements and loop through but I would like to combine it into a single statement.

I have this below, but want to improve it, as I am looping and hitting the calendar table twice each loop. I have tried With Select, lead and lag statements but none have worked.

Declare

cursor c1 is

select date1 from mytable;

p_current_period_std date;

p_next_period_std    date;

Begin

    FOR c1_rec IN c1

    Loop

    SELECT MAX (caldate) into p_current_period_std

    FROM caldates

    WHERE caldate <=c1_rec.date1;

    SELECT min (caldate) into p_next_period_std

    FROM caldates

    WHERE caldate >= c1_rec.date1;

-- Then do some updates based on date1, p_current_period_std and p_next_period_std

   

end loop;

End;

Comments
Post Details
Added on Jan 31 2020
3 comments
6,036 views