我有一个表格,其中的列包含' dd.mm.yyyy'格式。 例如:
_______________________
cnt_id | cnt_date |
-----------------------
1 | '15.01.2014' |
2 | '03.04.2014' |
3 | '10.05.2014' |
-----------------------
如何获取最短和最长日期之间的日期范围列表?
对于我的例子,正确的结果应该是:
15.01.2014 - 31.01.2014
01.02.2014 - 28.02.2014
01.03.2014 - 31.03.2014
01.04.2014 - 30.04.2014
01.05.2014 - 10.05.2014
我使用的是Oracle 11g,如果它确实重要的话。 感谢名单!
答案 0 :(得分:1)
你在这里: - )
with w1 as
( -- Get min and max dates
select min(to_date(t.cnt_date, 'dd.mm.yyyy')) min_date,
max(to_date(t.cnt_date, 'dd.mm.yyyy')) max_date
from <your_table> t
),
w2 as
( -- Get diff between them in months
select min_date, max_date,
to_number(to_char(max_date, 'MM'))
- to_number(to_char(min_date, 'MM')) delta
from w1
)
select w2.*, level,
-- Get min date if 1st range, else 1st day of month
case when level = 1
then min_date
else trunc(add_months(min_date, level - 1), 'MON')
end rleft,
-- Get max date if last range, else last day of month
case when level = delta + 1
then max_date
else trunc(add_months(min_date, level), 'MON') - 1
end rright
from w2
connect by level <= delta + 1 -- beware of + 1 to get ranges for all of them !
这给出了:
MIN_DATE MAX_DATE DELTA LEVEL RLEFT RRIGHT
15-janv.-2014 10-mai-2014 4 1 15-jan-2014 31-jan-2014
15-janv.-2014 10-mai-2014 4 2 01-feb-2014 28-feb-2014
15-janv.-2014 10-mai-2014 4 3 01-mar-2014 31-mar-2014
15-janv.-2014 10-mai-2014 4 4 01-apr-2014 30-apr-2014
15-janv.-2014 10-mai-2014 4 5 01-may-2014 10-may-2014