简体   繁体   中英

get the previous last date of the month in oracle sql

I have below query which is taking the last date of the month when this query is running on the current month. But as i am going to use this query in stored procedure and this procedure will run may be on the 1st or 2nd or 3rd of the current month then in this case i want to take the previous last month date everytime. For example if the query runs on 2nd or 3rd february then it will return the date with 31st January which is previous month last date.

The C_DATE column is date datatype

Select * from C_LOG
WHERE C_DATE = LAST_DAY(to_date(sysdate,'YYYYMMDD'))-1

You can use EXTRACT( DAY FROM SYSDATE ) to get the current day of the month. If this is below your threshold then you can get the last day of the previous month otherwise use the last day of the current month:

SELECT *
FROM   C_LOG
WHERE  C_DATE = CASE
                WHEN EXTRACT( DAY FROM SYSDATE ) <= 3
                THEN TRUNC( SYSDATE, 'MM' ) - INTERVAL '1' DAY
                ELSE LAST_DAY( TRUNC( SYSDATE ) )
                END

Note :

Do not use to_date(sysdate,'YYYYMMDD') since TO_DATE( date_string, format_model ) takes a string as its first argument so Oracle will implicitly cast the date to a string; effectively doing:

TO_DATE(
  TO_CHAR(
    SYSDATE,
    ( SELECT value FROM NLS_SESSION_PARAMETERS WHERE parameter = 'NLS_DATE_FORMAT' )
  ),
  'YYYYMMDD'
)

If the NLS_DATE_FORMAT is not YYYYMMDD then the query will fail. Since this is a session parameter, each user can change it at any time and your query will fail for any user who changes that parameter without ever changing sql of the query.

Instead, if you want to remove the time component of a DATE data type, use the TRUNC function.

you can use ADD_MONTHS function,

SELECT ADD_MONTHS(LAST_DAY(SYSDATE), -1) FROM DUAL;

you can also use the TRUNC function

SELECT TRUNC(SYSDATE, 'MM')-1 FROM DUAL;

Yet another variation:

SELECT *
  FROM c_log
 WHERE c_date =
          TRUNC (
             LAST_DAY (
                CASE
                   WHEN EXTRACT (DAY FROM SYSDATE) <= 3
                   THEN
                      ADD_MONTHS (SYSDATE, -1)
                   ELSE
                      SYSDATE
                END));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM