In the code below, the "D" subquery returns only valid dates in the DAY column, however, when you try to filter that column by using the WHERE clause, Oracle displays the following error message:
"ORA-01839: The date is not valid for the specified month"
How do I filter this column in the WHERE clause without this error appearing?
Code example without WHERE and without the error:
SELECT
D.DIA,
D.MES_ANO,
D.ULTIMO_DIA_MES
FROM
(
SELECT
TO_DATE(LPAD(TO_CHAR(C.DIA),2,'0') || '/' || C.MES_ANO, 'DD/MM/YYYY') DIA,
C.MES_ANO,
C.ULTIMO_DIA_MES
FROM
(
SELECT
B.DIA,
A.MES_ANO,
A.ULTIMO_DIA_MES
FROM
(
SELECT '04/2018' MES_ANO, TO_DATE('30/04/2018','DD/MM/YYYY') ULTIMO_DIA_MES FROM DUAL UNION ALL
SELECT '05/2018' MES_ANO, TO_DATE('31/05/2018','DD/MM/YYYY') ULTIMO_DIA_MES FROM DUAL UNION ALL
SELECT '06/2018' MES_ANO, TO_DATE('30/06/2018','DD/MM/YYYY') ULTIMO_DIA_MES FROM DUAL
) A,
( SELECT ROWNUM DIA FROM DUAL CONNECT BY ROWNUM <= 31 ) B
WHERE
B.DIA <= TO_NUMBER(TO_CHAR(A.ULTIMO_DIA_MES, 'DD'))
) C
) D
ORDER BY
D.DIA;
Code sample with WHERE and error:
SELECT
D.DIA,
D.MES_ANO,
D.ULTIMO_DIA_MES
FROM
(
SELECT
TO_DATE(LPAD(TO_CHAR(C.DIA),2,'0') || '/' || C.MES_ANO, 'DD/MM/YYYY') DIA,
C.MES_ANO,
C.ULTIMO_DIA_MES
FROM
(
SELECT
B.DIA,
A.MES_ANO,
A.ULTIMO_DIA_MES
FROM
(
SELECT '04/2018' MES_ANO, TO_DATE('30/04/2018','DD/MM/YYYY') ULTIMO_DIA_MES FROM DUAL UNION ALL
SELECT '05/2018' MES_ANO, TO_DATE('31/05/2018','DD/MM/YYYY') ULTIMO_DIA_MES FROM DUAL UNION ALL
SELECT '06/2018' MES_ANO, TO_DATE('30/06/2018','DD/MM/YYYY') ULTIMO_DIA_MES FROM DUAL
) A,
( SELECT ROWNUM DIA FROM DUAL CONNECT BY ROWNUM <= 31 ) B
WHERE
B.DIA <= TO_NUMBER(TO_CHAR(A.ULTIMO_DIA_MES, 'DD'))
) C
) D
WHERE
D.DIA < SYSDATE
ORDER BY
D.DIA;