如何从结束日期获取事件的开始日期和结束日期

时间:2012-06-04 07:45:28

标签: sql oracle10g

我有一个包含事件及其结束日期的表格如下 -

Event_id    Event_name        Event_end_date
1           Name Change       31-Mar-2010       (prior to 31-Mar-2010)
2           Parent change     31-Oct-2010       (Logically its duration is 1-Apr-2010 (31-Mar-2010 + 1(Day) ) to 31-Oct-2010)
3           Name Change       31-Jul-2011       (Logically its duration is 1-Nov-2010 (31-Oct-2010 + 1(Day) ) to 31-Jul-2011)

所以我想编写一个查询来获得如下结果 -

Event_id    Event_name     Event_start_date    Event_end_date
1           Name Change        -               31-Mar-2010
2           Parent change   1-Apr-2010         31-Oct-2010
3           Name Change     1-Nov-2010         31-Jul-2011

4 个答案:

答案 0 :(得分:2)

SELECT event_id, event_name,
   LAG (event_end_date ) OVER (ORDER BY event_end_date ASC )+1
                                                         event_start_date,
   event_end_date
 FROM event

enter image description here

答案 1 :(得分:2)

select event_id,
       event_name, 
       (lag(event_end_date) over (order by event_end_date)) + 1 as event_start_date, 
       event_end_date
from event_table
order by event_end_date desc

答案 2 :(得分:0)

这可以使用自我左外连接使用event_id来连接表来完成。

      select t1.Event_id ,t1.Event_name, coalesce(t2.Event_end_date,'-'),
             t1.Event_end_date
      from event_table t1 
                left outer join event_table t2 
      on t1.Event_id=t2.Event_id+1

这适用于mysql。也应该在oracle工作。

答案 3 :(得分:0)

我会用正则表达式来做:)

select event_id, 
       event_name, 
       REGEXP_SUBSTR(comments, ' \d+-\w{3}-\d{4} ') as event_start_date, 
       to_char(event_end_date,'dd-MON-yyyy')
from events

http://sqlfiddle.com/#!4/fa1e5/16/0