Forudsat at dine datoer altid har en tidskomponent ved midnat, så:
SELECT *
FROM your_table
WHERE your_date_column IN (
TRUNC( SYSDATE ),
TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY,
ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY, -12 ),
ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY, -24 ),
ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY, -36 ),
ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY, -48 )
);
(Du skal tilføje 1 dag før afkortning for at matche sagen, når i dag er den 31. december)
Den enkle løsning ville være at bruge TRUNC
på datoen.
SELECT *
FROM your_table
WHERE TRUNC( your_date_column ) IN (
TRUNC( SYSDATE ),
TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY,
ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY, -12 ),
ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY, -24 ),
ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY, -36 ),
ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY, -48 )
);
Men så kan du ikke bruge et indeks på kolonnen og ville have brug for et funktionsbaseret indeks på TRUNC( your_date_column )
for at kunne bruge et indeks.
Den mere komplicerede løsning, der kan bruge indekser, er:
SELECT *
FROM your_table
WHERE ( your_date_column >= TRUNC( sysdate )
AND your_date_column < TRUNC( sysdate ) + INTERVAL '1' DAY
)
OR ( your_date_column >= TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY
AND your_date_column < TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' )
)
OR ( your_date_column >= ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY, -12 )
AND your_date_column < ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ), -12 )
)
OR ( your_date_column >= ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY, -12 )
AND your_date_column < ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ), -24 )
)
OR ( your_date_column >= ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY, -12 )
AND your_date_column < ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ), -36 )
)
OR ( your_date_column >= ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ) - INTERVAL '1' DAY, -12 )
AND your_date_column < ADD_MONTHS( TRUNC( SYSDATE + INTERVAL '1' DAY, 'YYYY' ), -48 )
);