繁体   English   中英

Oracle SQL 如何获得一个月的第一天

[英]How Oracle SQL to get first day of month

要求是输入日期应该产生当月的第一天。 条件是:

  1. 如果输入的日期介于 11 月 1 日到 11 月 30 日之间,则第一天将是 11 月 1 日。
  2. 对于所有其他/下个月,它应该返回相应月份的第 1 天。

Ex: if i select Month OCT and Year 2021 then Startinvoice same with startbilldate and endinvoice get lastday of month from startinvoice but when i select Month NOV and Year 2021 then Startinvoice = 01 nov 2021 and endinvoice = 30 nov 2021 next month it should return 01st对应月份的日期。 在此处输入图像描述

您可以在这里使用CASE表达式:

SELECT
    dt,
    CASE WHEN EXTRACT(day FROM dt) <= 15
         THEN TRUNC(dt, 'MM')
         ELSE TRUNC(ADD_MONTHS(dt, 1), 'MM') END AS dt_out
FROM yourTable;

这些条件基本上是平等的。 无论如何,11 月有 30 天,所以您的第一个条件包含在第二个条件中。 完全没有区别。

因此,您只需将 date 值截断为month ,例如

SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';

Session altered.

SQL> select sysdate,
  2         trunc(sysdate, 'mm') first_of_month
  3  from dual;

SYSDATE             FIRST_OF_MONTH
------------------- -------------------
21.12.2021 09:01:22 01.12.2021 00:00:00

SQL>

暂无
暂无

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

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