如何在日期范围内重复选择查询?

时间:2013-08-12 08:45:22

标签: sql oracle plsql

我有一个包含“Date”列的表。日期将以循环形式显示在日历中。例如,记录日期将在每周的某一天显示在日历中,直到特定日期(比如TerminationDate)。在我的表中总结一下,我有Date和TerminationDate列,如下所示:

Table:
Title | Date | TerminationDate
------------------------------
t1    | d1   | td1

我希望实现这样的目标:

From query:
Title | Date | TerminationDate
------------------------------
t1    | d1+7 | td1
t1    | d1+14| td1
t1    | d1+21| td1
.................... till Date < TerminationDate

有没有人知道如何在Oracle中实现这一目标?

3 个答案:

答案 0 :(得分:1)

我没有测试过查询,但它应该像你需要的那样工作

    SELECT t1, d1 + (7 * LEVEL), termination_date
      FROM tab
     WHERE d1 + (7 * LEVEL) < termination_date
   CONNECT BY LEVEL <= CEIL( (termination_date - d1) / 7);

修改

SELECT DISTINCT t1,dt,termination_date
FROM( 
SELECT t1, d1 + (7 * LEVEL) dt, termination_date
  FROM tab
 WHERE d1 + (7 * LEVEL) < termination_date
CONNECT BY LEVEL <= CEIL( (termination_date - d1) / 7)
);

答案 1 :(得分:1)

这应该可以解决问题

select distinct title, date +  ( level * 7 ), termination_date 
 from table 
  connect by  date +  ( level * 7 ) < termination_date 

编辑:

忘记上面的查询,因为行必须只与自身连接,必须有

connect_by prior title = title 

但这意味着必须创建一个循环。不幸的是,如果存在循环,Oracle connect by子句会抛出错误。即使你使用

date +  ( level * 7 ) < termination_date 

Oracle在运行时检测到循环时仍会立即停止执行。使用nocycle返回结果,但只返回第一个记录,即日期+7

<强> ANSWER

所以我必须以不同的方式解决问题

select t.*, date + (r * 7) as the_date
 from table t,
   (select rownum as r
      from dual
    connect by level < (select max(weeks) --max date interval as weeks to be used to repeat each row as much, if you know the max weeks difference you can use the constant number instead of this sub-query
                          from (select ceil((termination_date - date) / 7) as weeks 
                                  from table ))
)
 where r < ceil((termination_date - date) / 7)

让我知道是否有任何疑惑或性能问题

答案 2 :(得分:0)

这是另一种方法

SELECT 
  *,
  date + ( ROWNUM * 7 ) as modified_date
FROM (
  SELECT 
    title, 
    date,
    termination_date 
  FROM 
   table 
 ) WHERE date + ( ROWNUM * 7 ) < termination_date