【问题标题】:Get first date of month in oracle在 oracle 中获取月份的第一个日期
【发布时间】:2015-11-21 14:48:36
【问题描述】:

我想获得开始日期和结束日期之间的不同月份。选定的月份日期将是相应月份的第一个日期。例如,我的开始日期是 01/30/2015 00:00:00,结束日期是 11/30/2015 23:59:59

我创建的查询:

with data1 as(
select to_date('01/30/2015 00:00:00','MM/DD/YYYY HH24:MI:SS')+level-1 dt 
  from dual
connect by level <= to_date('11/30/2015 23:59:59','MM/DD/YYYY HH24:MI:SS')-to_date('01/30/2015 00:00:00','MM/DD/YYYY HH24:MI:SS')+1)
select  distinct trunc(dt,'MM') as date1
  from data1
 where dt between to_date('01/30/2015 00:00:00','MM/DD/YYYY HH24:MI:SS') and to_date('11/30/2015 23:59:59','MM/DD/YYYY HH24:MI:SS')
   and trunc(dt,'MM') <= to_date('11/30/2015 23:59:59','MM/DD/YYYY HH24:MI:SS')
 order by trunc(dt,'MM')

输出:

01/01/2015 00:00:00  ,
02/01/2015 00:00:00  ,
03/01/2015 00:00:00  ,
04/01/2015 00:00:00  ,
05/01/2015 00:00:00  ,
06/01/2015 00:00:00  ,
07/01/2015 00:00:00  ,
08/01/2015 00:00:00  ,
09/01/2015 00:00:00  ,
10/01/2015 00:00:00  ,
11/01/2015 00:00:00

这个查询产生了正确的输出,但我怀疑上面的查询将在所有版本的 oracle 数据库中运行而没有任何问题。请给我指示。

【问题讨论】:

  • 此查询将在从 9.2 开始的版本上运行,因为早期版本不支持 WITH 子句。

标签: oracle


【解决方案1】:

您的查询将有效。但是使用ADD_MONTHS 可以以更直接的方式以更少的工作获得相同的结果。

select trunc(add_months(date '2015-01-30', level - 1), 'MONTH') as THE_MONTH
from dual
connect by trunc(add_months(date '2015-01-30', level - 1), 'MONTH')
    <= date '2015-11-30'
order by THE_MONTH

【讨论】:

  • @Prabha 特别注意 add_months 的行为方式:If date is the last day of the month or if the resulting month has fewer days than the day component of date, then the result is the last day of the resulting month. Otherwise, the result has the same day component as date.
猜你喜欢
  • 2012-12-23
  • 1970-01-01
  • 2020-01-17
  • 1970-01-01
  • 2021-12-07
  • 2016-12-26
  • 1970-01-01
  • 1970-01-01
  • 2011-05-28
相关资源
最近更新 更多