我想在开始和结束日期之间获得截然不同的月份。选定的月份日期将是相应月份的第一个日期。例如,我的开始日期是01/30/2015 00:00:00&结束日期是2015年11月30日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数据库中运行而没有任何问题。请给我指示。
答案 0 :(得分: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