sqloracle-databaseto-char

How to check for a specific date with a CASE statement in SQL in Oracle SQL


I am trying to write a statement in OracleSQL which will select the results from either yesterday or the last 3 days according to whether the date in a specific field (column3) is monday.

SELECT Column1, Column2, Column3 FROM Table
WHERE CASE
       WHEN To_Char(Column2, 'Day') = 'Monday'
          THEN Column3 >= (SYSDATE - Interval "3" Day)
       ELSE Column3 >= (SYSDATE - Interval "1" Day)
    END
Order by Column3 DESC; 

alternatively

SELECT Column1, Column2, Column3 FROM Table
WHERE Column3 >= 
    (CASE
       WHEN To_Char(Current_Date 'D') = 1
          THEN To_Char(Current_Date - 3)
       ELSE To_Char(Current_Date - 1)
    END
Order by Column3 DESC; 

For clarity, I have a table with many thousands of entries and I need to display only recent results from yesterday or from the weekend. The snippet is meant to read the date of entry from column3 and then either show the last 3 days or yesterday accordingly.

SOLVED: The ultimate code which worked--

SELECT Column1, Column2, Column3 FROM The_Table
WHERE Column3 >= 
    CASE
        WHEN to_char(Current_Date, 'fmDay', 'nls_date_language = English') = 'Monday'
            THEN TRUNC(SYSDATE) - INTERVAL '3' DAY
        ELSE TRUNC(SYSDATE) - INTERVAL '1' DAY
    END
ORDER BY Column3 DESC;

Solution

  • Something like this?

      SELECT column1, column2, column3
        FROM your_table
       WHERE column3 >=
             CASE
                WHEN TO_CHAR (column2, 'fmDay', 'nls_date_language = english') = 'Monday'
                THEN
                   TRUNC(SYSDATE) - INTERVAL '3' DAY
                ELSE
                   TRUNC(SYSDATE) - INTERVAL '1' DAY
             END
    ORDER BY column3 DESC;