日期后月份的第一天和最后一天的Oracle SQL Need列表

时间:2018-11-08 16:52:25

标签: oracle date

我希望有一个更优雅的查询,该查询可以从没有数据库的只读数据库中生成日期(例如2013年1月1日)后所有月份的月份的第一天和月份的最后一天的列表。日期表。我的解决方案有效,但困扰我。

我为我的蛮力解决方案预先道歉,但这是我今天使用的摘录。

select ((add_months(trunc(sysdate,'mm'),-1))) as FirstDOM, (last_day(add_months(trunc(sysdate,'mm'),-1))) as LASTDOM from dual union ALL 
select ((add_months(trunc(sysdate,'mm'),-2))), (last_day(add_months(trunc(sysdate,'mm'),-2))) from dual union ALL
select ((add_months(trunc(sysdate,'mm'),-3))), (last_day(add_months(trunc(sysdate,'mm'),-3))) from dual union ALL
select ((add_months(trunc(sysdate,'mm'),-4))), (last_day(add_months(trunc(sysdate,'mm'),-4))) from dual union ALL
select ((add_months(trunc(sysdate,'mm'),-5))), (last_day(add_months(trunc(sysdate,'mm'),-5))) from dual union ALL
select ((add_months(trunc(sysdate,'mm'),-6))), (last_day(add_months(trunc(sysdate,'mm'),-6))) from dual union ALL
select ((add_months(trunc(sysdate,'mm'),-7))), (last_day(add_months(trunc(sysdate,'mm'),-7))) from dual union ALL
select ((add_months(trunc(sysdate,'mm'),-8))), (last_day(add_months(trunc(sysdate,'mm'),-8))) from dual union ALL
select ((add_months(trunc(sysdate,'mm'),-9))), (last_day(add_months(trunc(sysdate,'mm'),-9))) from dual union ALL
select ((add_months(trunc(sysdate,'mm'),-10))), (last_day(add_months(trunc(sysdate,'mm'),-10))) from dual union ALL
select ((add_months(trunc(sysdate,'mm'),-11))), (last_day(add_months(trunc(sysdate,'mm'),-11))) from dual union ALL
select ((add_months(trunc(sysdate,'mm'),-12))), (last_day(add_months(trunc(sysdate,'mm'),-12))) from dual union ALL
select ((add_months(trunc(sysdate,'mm'),-13))), (last_day(add_months(trunc(sysdate,'mm'),-13))) from dual union ALL
select ((add_months(trunc(sysdate,'mm'),-14))), (last_day(add_months(trunc(sysdate,'mm'),-14))) from dual) fldom 

但实际上持续了60个月。
谢谢!

1 个答案:

答案 0 :(得分:1)

层次查询以一种简单的方式做到这一点。这是一个示例:

SQL> alter session set nls_date_format = 'dd.mm.yyyy';

Session altered.

SQL> set ver off
SQL> with test (col) as
  2    (select date '2013-01-01' from dual),
  3  all_months as
  4    (select add_months(col, level - 1) mon
  5     from test
  6     connect by level <= &number_of_months
  7    )
  8  select trunc(mon, 'mm') first_day,
  9    last_day(mon) last_day
 10  from all_months
 11  order by 1;
Enter value for number_of_months: 15

FIRST_DAY  LAST_DAY
---------- ----------
01.01.2013 31.01.2013
01.02.2013 28.02.2013
01.03.2013 31.03.2013
01.04.2013 30.04.2013
01.05.2013 31.05.2013
01.06.2013 30.06.2013
01.07.2013 31.07.2013
01.08.2013 31.08.2013
01.09.2013 30.09.2013
01.10.2013 31.10.2013
01.11.2013 30.11.2013
01.12.2013 31.12.2013
01.01.2014 31.01.2014
01.02.2014 28.02.2014
01.03.2014 31.03.2014

15 rows selected.

SQL>

仅举一个例子,我选择显示15个月。您可以使用其他值,例如固定值(60-您提到的值)或计算值(例如,使用MONTHS_BETWEEN)。