I have a problem again and can't ask anyone at the moment. I want to include a switch-case in a SQL SELECT which filters by date.
The goal is to display a simple grid in a window and filter my data by a date "where".
On the one hand I want to search for everything that exists in the year = e.g. '2022'.
Then I want to search only for calendar weeks = e.g. '23'.
Then show me only the month = eg. '07'
and just the complete date = e.g. '22.07.2022'.
SELECT
ID
, GEN_DATUM
FROM
TABLE_XY
WHERE
CASE
WHEN '{DATUM_MODUS}' = '#JA' THEN TO_CHAR(GEN_DATUM, 'yyyy') = TO_CHAR('{DATUM}' , 'yyyy')
WHEN '{DATUM_MODUS}' = '#KW' THEN TO_CHAR(GEN_DATUM, 'IW') = TO_CHAR('{DATUM}' , 'IW')
WHEN '{DATUM_MODUS}' = '#MO' THEN TO_CHAR(GEN_DATUM, 'MM') = TO_CHAR('{DATUM}' , 'MM')
WHEN '{DATUM_MODUS}' = '#WO' THEN TO_CHAR(GEN_DATUM, 'DD.MM.YYYY') = TO_CHAR('{DATUM}' , 'MM')
ELSE NULL
END
In the source code I pass parameters that I need for further processing. Here I want to say
if I want to search for year 'DATUM_MODUS' = #JA then show me the year
System.Collections.Hashtable htPARAM = new System.Collections.Hashtable()
{
["DATUM"] = Datum,
["DATUM_MODUS"] = Datum_MODUS,
};
Use AND and OR rather than a CASE expression.
Never build an SQL statement using string concatenation or template strings as you introduce SQL injection vulnerabilities; use bind variables instead.
If you use functions on the gen_datum column then Oracle will not be able to use an index on that column (and would require function-based indexes instead). Instead, change the datum value into a date and match the start and end of each date range and then Oracle can use an index on the gen_datum column.
Like this:
SELECT ID
, GEN_DATUM
FROM TABLE_XY
WHERE ( :datum_modus = '#JA'
-- Search by year
AND gen_datum >= TO_DATE(:datum || '-01-01', 'YYYY-MM-DD')
AND gen_datum < TO_DATE((:datum + 1) || '-01-01', 'YYYY-MM-DD')
)
OR ( :datum_modus = '#KW'
-- Search by ISO week in the current year
AND gen_datum >= TRUNC(TRUNC(SYSDATE, 'YY') + 3, 'IW') + 7 * (:datum - 1)
AND gen_datum < TRUNC(TRUNC(SYSDATE, 'YY') + 3, 'IW') + 7 * :datum
)
OR ( :datum_modus = '#MO'
-- Search by month in the current year
AND gen_datum >= ADD_MONTHS(TRUNC(SYSDATE, 'YY'), :datum - 1)
AND gen_datum < ADD_MONTHS(TRUNC(SYSDATE, 'YY'), :datum)
)
OR ( :datum_modus = '#WO'
-- Search by date
AND gen_datum >= TO_DATE(:datum, 'DD.MM.YYYY')
AND gen_datum < TO_DATE(:datum, 'DD.MM.YYYY') + 1
)
The with clause is here just to generate some sample data and, as such, it is not a part of the answer.
You missunderstood the CASE expression. CASE expression returns a value and you are trying to get another expression out of it. Also you have to keep in mind
that CASE is tested sequentially meaning that the first one with WHEN condition satisfied will return the THEN part and EXIT CASE.
Having that in mind all you have to do is compare two CASE expresions (two returned values) and try to get the result. WHEN clauses in both of them should be rearrenged too.
Try something like this:
WITH
tbl AS
(
SELECT 1 "ID", To_Date('08.01.2022', 'dd.mm.yyyy') "GEN_DATUM" FROM DUAL UNION ALL
SELECT 2 "ID", To_Date('23.04.2022', 'dd.mm.yyyy') FROM DUAL UNION ALL
SELECT 3 "ID", To_Date('17.06.2022', 'dd.mm.yyyy') FROM DUAL UNION ALL
SELECT 4 "ID", To_Date('19.06.2022', 'dd.mm.yyyy') FROM DUAL
)
SELECT
ID,
TO_CHAR(GEN_DATUM, 'dd.mm.yyyy') "GEN_DATUM",
TO_CHAR(GEN_DATUM, 'iw') "WEEK_OF_GEN_DATUM",
TO_CHAR(GEN_DATUM, 'mm') "MONTH_OF_GEN_DATUM",
TO_CHAR(GEN_DATUM, 'yyyy') "YEAR_OF_GEN_DATUM",
:DATUM_MODUS "DATUM_MODUS",
TO_CHAR(:DATUM, 'dd.mm.yyyy') "DATUM"
FROM
tbl
WHERE
CASE
WHEN :DATUM_MODUS = '#WO' THEN TO_CHAR(GEN_DATUM, 'dd.mm.yyyy') -- the most distinctive (365)
WHEN :DATUM_MODUS = '#KW' THEN TO_CHAR(GEN_DATUM, 'iw') -- second (52)
WHEN :DATUM_MODUS = '#MO' THEN TO_CHAR(GEN_DATUM, 'mm') -- next (12)
WHEN :DATUM_MODUS = '#JA' THEN TO_CHAR(GEN_DATUM, 'yyyy') -- the most undistinctive (1)
ELSE
NULL
END
=
CASE
WHEN :DATUM_MODUS = '#WO' THEN TO_CHAR(:DATUM, 'dd.mm.yyyy')
WHEN :DATUM_MODUS = '#KW' THEN TO_CHAR(:DATUM, 'iw')
WHEN :DATUM_MODUS = '#MO' THEN TO_CHAR(:DATUM, 'mm')
WHEN :DATUM_MODUS = '#JA' THEN TO_CHAR(:DATUM, 'yyyy')
ELSE
NULL
END
--
-- If you use bind variables :DATUM_MODUS = '#KW' and :DATUM = To_Date('19.06.2022', 'dd.mm.yyyy') the result is:
-- ID GEN_DATUM WEEK_OF_GEN_DATUM MONTH_OF_GEN_DATUM YEAR_OF_GEN_DATUM DATUM_MODUS DATUM
-- ---------- ---------- ----------------- ------------------ ----------------- ----------- ----------
-- 3 17.06.2022 24 06 2022 #KW 19.06.2022
-- 4 19.06.2022 24 06 2022 #KW 19.06.2022
--
-- For :DATUM_MODUS = '#MO' and :DATUM = To_Date('14.01.2022', 'dd.mm.yyyy') the result is:
-- ID GEN_DATUM WEEK_OF_GEN_DATUM MONTH_OF_GEN_DATUM YEAR_OF_GEN_DATUM DATUM_MODUS DATUM
-- ---------- ---------- ----------------- ------------------ ----------------- ----------- ----------
-- 1 08.01.2022 01 01 2022 #MO 14.01.2022
... and so on....
In the SELECT part there are all the values involved so you can check the results and/or (if needed) filter them even more if you make this a subquery of a main one. In that case you can manipulate the data further more. Regards...
Related
SELECT * FROM dummy;
act_date
---------
27-JAN-22
SELECT * FROM dummy1;
rpt_date
---------
10-JAN-22
10-DEC-21
how to get only Saturdays between act_date of dummy and MIN(rpt_date) of dummy1 table in Oracle's SQL?
please help
Here is a simple example of how to list all saturdays between 2 dates, you should be able to convert this to your data model.
WITH dummy(start_date, end_date) AS
(
SELECT DATE'2014-01-30', DATE'2014-02-25' FROM dual
), dummy_all_dates(dt) AS
(
SELECT
e.dt
FROM
dummy d CROSS APPLY
( SELECT
d.start_date + level - 1 AS dt
FROM dual CONNECT BY level < d.end_date - d.start_date
) e
)
SELECT dt FROM dummy_all_dates
WHERE TO_CHAR(dt,'FMDAY','NLS_DATE_LANGUAGE=english') = 'SATURDAY';
01-FEB-2014
08-FEB-2014
15-FEB-2014
22-FEB-2014
Here's another method to get a years worth of Saturdays. Adjust the dates as needed.
The to_char function has various format masks you can use to extract the day-of-week from a date. This uses day to get the full day name:
with rws as (
select date'2021-12-31' + level dt
from dual
connect by level <= (
date'2022-01-01' - date'2021-01-01'
)
)
select dt
from rws
where to_char (
dt,
'fmday',
'nls_date_language = English'
) = 'saturday';
This is the simplest of all answers:
select dt,rtrim(to_char(dt, 'DAY')) from (select to_date(SELECT
min(rpt_date)
FROM dummy1, 'DD-MON-YY') + rownum -1 dt
from all_objects
where rownum <= to_date((SELECT act_date FROM dummy), 'DD-MON-YY') -
to_date(SELECT min(rpt_date) FROM dummy1, 'DD-MON-YY'));
where rtrim(to_char(dt, 'DAY')) = 'SATURDAY';
Thanks!!
Oracle (SQL) - I have 3 available dates in a month (1st, 10th and 25th). I need a query to find out the closest among the 3 dates based on the date of executing my query. For e.g, when i run the query on 4th, i should get 10th as my result, when i run on 12th, the result should be 25th and when i run on 27th, the result should be the 01st of next month.
I am struggling with the logic. Please help..
with
inputs ( dt ) as (
select to_date( '03/24/2015 11:30:00', 'mm/dd/yyyy hh24:mi:ss') from dual union all
select to_date( '08/03/2016 07:15:00', 'mm/dd/yyyy hh24:mi:ss') from dual union all
select to_date( '02/29/2016 22:30:00', 'mm/dd/yyyy hh24:mi:ss') from dual
)
-- End of simulated inputs (for testing only, not part of the solution).
-- SQL query begins BELOW THIS LINE. Use your actual table and column names.
select dt,
case when extract(day from dt) < 10 then trunc(dt, 'mm') + interval '9' day
when extract(day from dt) < 25 then trunc(dt, 'mm') + interval '24' day
else add_months(trunc(dt, 'mm'), 1)
end as next_std_dt
from inputs;
DT NEXT_STD_DT
------------------- -------------------
03/24/2015 11:30:00 03/25/2015 00:00:00
08/03/2016 07:15:00 08/10/2016 00:00:00
02/29/2016 22:30:00 03/01/2016 00:00:00
I believe this is much more efficient and simpler than the other solutions.
WITH
possible_dates
AS
-- generate the three available dates for the current month
(SELECT TRUNC (SYSDATE, 'MM') available_date
FROM DUAL
UNION ALL
SELECT TRUNC (SYSDATE, 'MM') + 9
FROM DUAL
UNION ALL
SELECT TRUNC (SYSDATE, 'MM') + 24
FROM DUAL
UNION ALL
SELECT ADD_MONTHS (TRUNC (SYSDATE, 'MM'), 1)
FROM DUAL),
delta
AS
-- calculate the distance of those available dates
(SELECT (available_date - SYSDATE) diff, available_date
FROM possible_dates)
SELECT *
FROM delta
WHERE diff = (SELECT MIN (diff)
FROM delta
WHERE diff >= 0);
If using PL SQL is an option, then use the query as following:
`DECLARE
curr_month CHAR(2);
curr_year CHAR(4);
future_date DATE;
BEGIN
select to_char(sysdate, 'MM') INTO curr_month from dual;
select to_char(sysdate, 'YYYY') INTO curr_year from dual;
future_date := TO_DATE('12' || curr_month || curr_year, 'DD/MM/YYYY');
IF (SYSDATE > future_date) THEN
{..whatever you want to do...}
ELSIF (SYSDATE > future_date2) THEN
{..whatever you want to do...}
END IF;
END;`
WITH mytable(dt) AS
(SELECT '01'
FROM dual
UNION ALL SELECT '10'
FROM dual
UNION ALL SELECT '25'
FROM dual),
given_dates AS
(SELECT Trunc (To_date (dt || To_char(sysdate, 'MMYYYY'), 'DDMMYYYY')) dt,
Trunc(sysdate) cdate
FROM mytable),
comp AS
(SELECT cdate,
CASE
WHEN ABS (cdate - dt) < ABS (cdate - Add_months (dt, 1)) THEN dt
ELSE Add_months (dt, 1)
END dt_comp
FROM given_dates)
SELECT dt_comp closest_date
FROM
(SELECT dt_comp,
rank() OVER (
ORDER BY ABS (cdate - dt_comp)) rn
FROM comp)
WHERE rn = 1;
Is there any way i can calculate the first and last day of the three quarters in any year . 2012 , 2013 or 2014
SELECT ADD_MONTHS(TRUNC(SYSDATE, 'Q'), -3) AS First,
TRUNC(SYSDATE, 'Q') - 1 AS Last
FROM DUAL
calculates the first quarter of current year. i want to calculate the first quarter of any year ?
You could do the following:
with q(qtr) as(
select add_months(
DATE '2013-01-01'
, (level-1)*3
)
from dual
connect by level <= 4
)
select qtr as first_day
, last_day(add_months(qtr, 2)) as last_day
from q
Result:
FIRST_DAY LAST_DAY
----------- -----------
01.01.2013 31.03.2013
01.04.2013 30.06.2013
01.07.2013 30.09.2013
01.10.2013 31.12.2013
SQLFIddle Demo
This is one way of doing it
select to_date('01-JAN-'||to_char(yr), 'DD-MON-YYYY') first_qtr,
to_date('01-APR-'||to_char(yr), 'DD-MON-YYYY') second_qtr,
to_date('01-JUL-'||to_char(yr), 'DD-MON-YYYY') third_qtr,
to_date('01-OCT-'||to_char(yr), 'DD-MON-YYYY') fourth_qtr
from ( select :year yr from dual )
UNION ALL
select to_date('01-APR-'||to_char(yr), 'DD-MON-YYYY')-1 first_qtr,
to_date('01-JUL-'||to_char(yr), 'DD-MON-YYYY')-1 second_qtr,
to_date('01-OCT-'||to_char(yr), 'DD-MON-YYYY')-1 third_qtr,
to_date('01-JAN-'||to_char(yr+1), 'DD-MON-YYYY')-1 fourth_qtr
from ( select :year yr from dual )
I have used bind variables so change it to your requirements accordingly.
I am fairly new to Oracle, so other's can give a simplified code.
The output when given 2009 would be as below
FIRST_QTR SECOND_QTR THIRD_QTR FOURTH_QTR
01/01/2009 04/01/2009 07/01/2009 10/01/2009
03/31/2009 06/30/2009 09/30/2009 12/31/2009
This is an old question but maybe this will be helpful:
WITH y1 AS (
SELECT LEVEL + 2000 AS the_year
FROM dual
CONNECT BY LEVEL <= 20
), q1 AS (
SELECT LEVEL AS the_quarter
FROM dual
CONNECT BY LEVEL <= 4
)
SELECT the_year, the_quarter
, TO_CHAR(first_day, 'DAY') AS first_dw, first_day
, TO_CHAR(last_day, 'DAY') AS last_dw, last_day
FROM (
SELECT the_year, the_quarter
, ADD_MONTHS(TO_DATE(the_year, 'YYYY'), 3 * (the_quarter - 1)) AS first_day
, ADD_MONTHS(TO_DATE(the_year, 'YYYY'), 3 * the_quarter) - 1 AS last_day
FROM y1, q1
)
One line per year, each line consisting of the year plus 8 (=2 dates per quarter) dates:
with params as (
select
2012 as start_year,
2014 as end_year
from
dual
)
select
start_year+ level - 1 year,
to_date((start_year+ level - 1) || '0101', 'yyyymmdd') start_q1,
to_date((start_year+ level - 1) || '0331', 'yyyymmdd') end_q1 ,
to_date((start_year+ level - 1) || '0401', 'yyyymmdd') start_q2,
to_date((start_year+ level - 1) || '0630', 'yyyymmdd') end_q2 ,
to_date((start_year+ level - 1) || '0701', 'yyyymmdd') start_q3,
to_date((start_year+ level - 1) || '0930', 'yyyymmdd') end_q3 ,
to_date((start_year+ level - 1) || '1001', 'yyyymmdd') start_q4,
to_date((start_year+ level - 1) || '1231', 'yyyymmdd') end_q4
from
dual, params
connect by
start_year + level -1 <= end_year;
I have
Year : 2011
Month: Nov
Day: Sun
WeekNumber(Monthwise): 4
Desire Output:
Date
--------
2011-11-20
How can I do so in a single SQL statement?
Thanks
I'd probably look at using the NEXT_DAY function which returns the first day of the weekday provided that occurs after the date given. Once you've got that, you can then add the required number of weeks.
An example of this might be:
with test_data as (
select
'2011' as the_year,
'Nov' as the_month,
'Sun' as the_day,
4 as the_week
from dual
)
select
the_year, the_month, the_day, the_week,
next_day(to_date(the_year||the_month, 'YYYYMON') - 1, the_day) +
7* (the_week -1) as the_date
from test_data
this may work.
SELECT NEXT_DAY( TO_DATE(TO_CHAR((4-1)*7) || '-' || 'NOV' || '-' || '2011','dd-mon-yyyy') ,'Sun')
FROM DUAL
see: http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions093.htm
try :
SELECT A.B + B.D YourDate
FROM (SELECT TO_DATE (Your4DigitYear || LPAD ( YourMonth, 2, '0' ) || LPAD ( DECODE (YourWeekOfMonth, 1, '1', (YourWeekOfMonth - 1) * 7 ), 2, '0' ), 'YYYYMMDD') B FROM DUAL) A, (SELECT LEVEL - 1 D FROM DUAL CONNECT BY LEVEL < 15) B WHERE
TO_CHAR (A.B + B.D, 'D' ) = YourDayOfWeek AND
TO_CHAR (A.B + B.D, 'W' ) = YourWeekOfMonth;
See the results of below queries:
>> SELECT ADD_MONTHS(TO_DATE('30-MAR-11','DD-MON-RR'),-4) FROM DUAL;
30-NOV-10
>> SELECT ADD_MONTHS(TO_DATE('30-NOV-10','DD-MON-RR'),4) FROM DUAL;
31-MAR-11
How can I get '30-MAR-11' when adding 4 months to some date?
Please help.
There is another question here about Oracle and Java
It states that
From the Oracle reference on add_months http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14200/functions004.htm
If date is the last day of the month or if the resulting month has fewer days than the day component of date, then the result is the last day of the resulting month. Otherwise, the result has the same day component as date.
So I guess you have to manually check stating day and ending day to change the behaviour of the function. Or maybe by adding days instead of months. (But I didn't find a add_day function in the ref)
As a workaround, I might possibly use this algorithm:
Calculate the target date TargetDate1 using ADD_MONTHS.
Alternatively calculate the target date TargetDate2 like this:
1) apply ADD_MONTHS to the first of the source date's month;
2) add the difference of days between the source date and the beginning of the same month.
Select the LEAST between the TargetDate1 and TargetDate2.
So in the end, the target date will contain a different day component if the source date's day component is greater than the number of day in the target month. In this case the target date will be the last day of the corresponding month.
I'm not really sure about my knowledge of Oracle's SQL syntax, but basically the implementation might look like this:
SELECT
LEAST(
ADD_MONTHS(SourceDate, Months),
ADD_MONTHS(TRUNC(SourceDate, 'MONTH'), Months)
+ (SourceDate - TRUNC(SourceDate, 'MONTH'))
) AS TargetDate
FROM (
SELECT
TO_DATE('30-NOV-10', 'DD-MON-RR') AS SourceDate,
4 AS Months
FROM DUAL
)
Here is a detailed illustration of how the method works:
SourceDate = '30-NOV-10'
Months = 4
TargetDate1 = ADD_MONTHS('30-NOV-10', 4) = '31-MAR-11' /* unacceptable */
TargetDate2 = ADD_MONTHS('01-NOV-10', 4) + (30 - 1)
= '01-MAR-11' + 29 = '30-MAR-11' /* acceptable */
TargetDate = LEAST('31-MAR-11', '30-MAR-11') = '30-MAR-11'
And here are some more examples to show different cases:
SourceDate | Months | TargetDate1 | TargetDate2 | TargetDate
-----------+--------+-------------+-------------+-----------
29-NOV-10 | 4 | 29-MAR-11 | 29-MAR-11 | 29-MAR-11
30-MAR-11 | -4 | 30-NOV-10 | 30-NOV-10 | 30-NOV-10
31-MAR-11 | -4 | 30-NOV-10 | 01-DEC-10 | 30-NOV-10
30-NOV-10 | 3 | 28-FEB-11 | 02-MAR-11 | 28-FEB-11
You can use interval arithmetic to get the result you want
SQL> select date '2011-03-30' - interval '4' month
2 from dual;
DATE'2011
---------
30-NOV-10
SQL> ed
Wrote file afiedt.buf
1 select date '2010-11-30' + interval '4' month
2* from dual
SQL> /
DATE'2010
---------
30-MAR-11
Be aware, however, that there are pitfalls to interval arithmetic if you're working with days that don't exist in every month
SQL> ed
Wrote file afiedt.buf
1 select date '2011-03-31' + interval '1' month
2* from dual
SQL> /
select date '2011-03-31' + interval '1' month
*
ERROR at line 1:
ORA-01839: date not valid for month specified
How about something like this:
SELECT
LEAST(
ADD_MONTHS(TO_DATE('30-MAR-11','DD-MON-RR'),-4),
ADD_MONTHS(TO_DATE('30-MAR-11','DD-MON-RR')-1,-4)+1
)
FROM
DUAL
;
Result: 30-NOV-10
SELECT
LEAST(
ADD_MONTHS(TO_DATE('30-NOV-10','DD-MON-RR'),4),
ADD_MONTHS(TO_DATE('30-NOV-10','DD-MON-RR')-1,4)+1
)
FROM
DUAL
;
Result: 30-MAR-11
the add_months function returns a date plus n months.
Since 30th November is the last date of the month, adding 4 months will result in a date that's the end of 4 months. This is expected behavior. If the dates are not bound to change, a workaround is to subtract a day after the new date has been returned
SQL> SELECT ADD_MONTHS(TO_DATE('30-NOV-10','DD-MON-RR'),4) -1 from dual;
ADD_MONTH
---------
30-MAR-11
SELECT TO_DATE('30-NOV-10','DD-MON-RR') +
(
ADD_MONTHS(TRUNC(TO_DATE('30-NOV-10','DD-MON-RR'),'MM'),4) -
TRUNC(TO_DATE('30-NOV-10','DD-MON-RR'),'MM')
) RESULT
FROM DUAL;
This section in paranthesis:
ADD_MONTHS(TRUNC(TO_DATE('30-NOV-10','DD-MON-RR'),'MM'),4) - TRUNC(TO_DATE('30-NOV-10','DD-MON-RR'),'MM')
gives you number of days between the date you entered and 4 months later. So, adding this number of days to the date you given gives the exact date after 4 months.
Ref: http://www.dba-oracle.com/t_test_data_date_generation_sql.htm
Simple solution:
ADD_MONTHS(date - 1, x) + 1
Here is the trick:
select add_months(to_date('20160228', 'YYYYMMDD')-1, 1)+1 from dual;
Enjoy!
We have come to simpler (in our understanding) solution to this problem - take the least day number from original and add_month result dates, as this:
TRUNC(ADD_MONTHS(input_date,1),'MM') + LEAST(TO_CHAR(input_date, 'DD'), TO_CHAR(ADD_MONTHS(input_date,1), 'DD')) - 1
Some other examples here do not work on every date, below our test results:
WITH DATES as (
SELECT TO_DATE('2020-01-31', 'YYYY-MM-DD HH24:MI:SS') as input_date,
'2020-02-29' as expected_date
FROM dual
UNION ALL
SELECT TO_DATE('2020-02-28', 'YYYY-MM-DD HH24:MI:SS'),
'2020-03-28'
FROM dual
UNION ALL
SELECT TO_DATE('2020-09-30', 'YYYY-MM-DD HH24:MI:SS'),
'2020-10-30'
FROM dual
UNION ALL
SELECT TO_DATE('2020-09-01', 'YYYY-MM-DD HH24:MI:SS'),
'2020-10-01'
FROM dual
UNION ALL
SELECT TO_DATE('2019-01-30', 'YYYY-MM-DD HH24:MI:SS'),
'2019-02-28'
FROM dual
UNION ALL
SELECT TO_DATE('2020-02-29', 'YYYY-MM-DD HH24:MI:SS'),
'2020-03-29'
FROM dual
UNION ALL
SELECT TO_DATE('2020-09-29', 'YYYY-MM-DD HH24:MI:SS'),
'2020-10-29'
FROM dual
UNION ALL
SELECT TO_DATE('2020-03-01', 'YYYY-MM-DD HH24:MI:SS'),
'2020-04-01'
FROM dual
),
methods as (
SELECT
input_date,
expected_date,
ADD_MONTHS(input_date,1) as standard_way,
add_months(input_date-1, 1)+1 as wrong_way,
TO_DATE(LEAST(TO_CHAR(input_date, 'DD'), TO_CHAR(ADD_MONTHS(input_date,1), 'DD')) || '-' || TO_CHAR(ADD_MONTHS(input_date,1), 'MM-YYYY'), 'DD-MM-YYYY') as good_way,
TRUNC(ADD_MONTHS(input_date,1),'MM') + LEAST(TO_CHAR(input_date, 'DD'), TO_CHAR(ADD_MONTHS(input_date,1), 'DD')) - 1 as better_way
FROM
DATES
)
SELECT
input_date,
expected_date,
standard_way,
CASE WHEN TO_CHAR(standard_way,'YYYY-MM-DD') = expected_date THEN 'OK' ELSE 'NOK' END as standard_way_ok,
wrong_way,
CASE WHEN TO_CHAR(wrong_way,'YYYY-MM-DD') = expected_date THEN 'OK' ELSE 'NOK' END as wrong_way_ok,
good_way,
CASE WHEN TO_CHAR(good_way,'YYYY-MM-DD') = expected_date THEN 'OK' ELSE 'NOK' END as good_way_ok,
better_way,
CASE WHEN TO_CHAR(better_way,'YYYY-MM-DD') = expected_date THEN 'OK' ELSE 'NOK' END as better_way_ok
FROM
methods
;
CREATE OR REPLACE FUNCTION My_Add_Month(
STARTDATE DATE,
MONTHS_TO_ADD NUMBER
)
RETURN DATE
IS
MY_ADD_MONTH_RESULT DATE;
BEGIN
SELECT ORACLES_ADD_MONTH_RESULT + NET_DAYS_TO_ADJUST INTO MY_ADD_MONTH_RESULT FROM
(
SELECT T.*,CASE WHEN SUBSTRACT_DAYS > ADD_DAYS THEN ADD_DAYS - SUBSTRACT_DAYS ELSE 0 END AS NET_DAYS_TO_ADJUST FROM
(
SELECT T.*,EXTRACT(DAY FROM ORACLES_ADD_MONTH_RESULT) AS SUBSTRACT_DAYS FROM
(
SELECT ADD_MONTHS(STARTDATE,MONTHS_TO_ADD) AS ORACLES_ADD_MONTH_RESULT,EXTRACT(DAY FROM STARTDATE) AS ADD_DAYS FROM DUAL
)T
)T
)T;
RETURN TRUNC(MY_ADD_MONTH_RESULT);
END My_Add_Month;
/
--test & verification of logic & function both
SELECT T.*,ORACLES_ADD_MONTH_RESULT + NET_DAYS_TO_ADJUST AS MY_ADD_MONTH_RESULT,
My_Add_Month(STARTDATE,MONTHS_TO_ADD) MY_ADD_MONTH_FUNCTION_RESULT
FROM
(
SELECT T.*,CASE WHEN SUBSTRACT_DAYS > ADD_DAYS THEN ADD_DAYS - SUBSTRACT_DAYS ELSE 0 END AS NET_DAYS_TO_ADJUST FROM
(
SELECT T.*,EXTRACT(DAY FROM ORACLES_ADD_MONTH_RESULT) AS SUBSTRACT_DAYS FROM
(
SELECT T.*,ADD_MONTHS(STARTDATE,MONTHS_TO_ADD) AS ORACLES_ADD_MONTH_RESULT,EXTRACT(DAY FROM STARTDATE) AS ADD_DAYS FROM
(
SELECT TO_DATE('28/02/2014','DD/MM/YYYY') AS STARTDATE, 1 AS MONTHS_TO_ADD FROM DUAL
)T
)T
)T
)T;
Query-result
STARTDATE 2/28/2014
MONTHS_TO_ADD 1
ORACLES_ADD_MONTH_RESULT 3/31/2014
ADD_DAYS 28
SUBSTRACT_DAYS 31
NET_DAYS_TO_ADJUST -3
MY_ADD_MONTH_RESULT 3/28/2014
MY_ADD_MONTH_FUNCTION_RESULT 3/28/2014