问题
How can I subtract a number of months from a date, to produce a different date?
- var date_A = 24-06-2016
- var date_B = 24-01-2016
- var x = 5
Please how can I use the value in x (number of months) to calculate the value for date_B, from the value date_A?
回答1:
You can use the add_months() function:
select add_months(to_date('24-06-2016', 'DD-MM-YYYY'), -5) from dual;
ADD_MONTHS(TO_DATE('24-06-2016','DD-MM-YYYY'),-6)
-------------------------------------------------
2015-12-24
With SQL*Plus or SQL Developer bind variables (not sure if that's what you have) you can do:
var date_a varchar2(10);
var date_b varchar2(10);
var x number;
exec :date_a := '24-06-2016';
exec :x := 5;
exec :date_b := to_char(add_months(to_date(:date_a, 'DD-MM-YYYY'), -:x), 'DD-MM-YYYY');
print date_b
DATE_B
------
24-01-2016
if you want each of the previous five months, and the current month, you can use a dummy hierarchical query:
select add_months(to_date('24-06-2016', 'DD-MM-YYYY'), 1-level)
from dual
connect by level <= 6;
ADD_MONTHS(TO_DATE('24-06-2016','DD-MM-YYYY'),1-LEVEL)
------------------------------------------------------
2016-06-24
2016-05-24
2016-04-24
2016-03-24
2016-02-24
2016-01-24
Or if you actually have the start and end date, rather than the end date and x
, you can do:
select add_months(to_date('24-06-2016', 'DD-MM-YYYY'), 1-level)
from dual
connect by add_months(to_date('24-06-2016', 'DD-MM-YYYY'), 1-level)
>= to_date('24-01-2016', 'DD-MM-YYYY');
ADD_MONTHS(TO_DATE('24-06-2016','DD-MM-YYYY'),1-LEVEL)
------------------------------------------------------
2016-06-24
2016-05-24
2016-04-24
2016-03-24
2016-02-24
2016-01-24
Or you could use recursive subquery factoring instead of the connect by
syntax if you prefer, and you're on 11gR2 or higher:
with r (dt) as (
select to_date('24-06-2016', 'DD-MM-YYYY') from dual
union all
select add_months(r.dt, -1) from r
where add_months(r.dt, -1) >= to_date('24-01-2016', 'DD-MM-YYYY')
)
select r.dt
from r
order by r.dt desc;
You can use bind variables for the dates or upper limit in those queries too.
回答2:
If you want to subtract x
months from date_A
, it's:
add_months(date_A, x * -1)
Edit: Alex beat me to it, and there is a new requirement :(
来源:https://stackoverflow.com/questions/39128559/return-list-of-date-using-a-set-value