简体   繁体   English

在oracle sql中获取月份的上一个最后日期

[英]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. 但是由于我将在存储过程中使用此查询,并且此过程将在本月的1号,2号或3号运行,因此在这种情况下,我希望每次取上一个上月的日期。 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. 例如,如果查询在2月2日或2月3日运行,则它将返回1月31日的日期,该日期是上个月的上一个日期。

The C_DATE column is date datatype C_DATE列是日期数据类型

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. 您可以使用EXTRACT( DAY FROM SYSDATE )获取月份的当前日期。 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; 不要使用to_date(sysdate,'YYYYMMDD')因为TO_DATE( date_string, format_model )将字符串作为第一个参数,因此Oracle会将日期隐式转换为字符串。 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. 如果NLS_DATE_FORMAT不是YYYYMMDD则查询将失败。 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. 由于这是一个会话参数,因此每个用户都可以随时更改它,并且任何更改该参数而不更改查询的sql的用户的查询都会失败。

Instead, if you want to remove the time component of a DATE data type, use the TRUNC function. 相反,如果要删除DATE数据类型的时间分量,请使用TRUNC函数。

you can use ADD_MONTHS function, 您可以使用ADD_MONTHS函数,

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

you can also use the TRUNC function 您也可以使用TRUNC功能

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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