0
Row No. Start Date  End Date
1   28/11/2012           28/11/2012
2   28/11/2012            6/12/2012
3   6/12/2012             6/12/2012
4   22/01/2013           23/01/2013
5   23/01/2013  

根据上述示例数据,我有以下两个查询:-

  1. SQL 将记录带入日期不连续的地方(例如,rrecord 3 于 2012 年 6 月 12 日结束,但记录 4 于 2013 年 1 月 22 日开始)

  2. 调整日期不连续的日期(例如,将记录 4 的开始日期更新为 2012 年 6 月 12 日以保持连续性)

提前感谢哈利

4

2 回答 2

1

SELECT 语句很简单:

select * from your_table t1
where t1.end_date is not null
and not exists
   ( select null from your_table t2
     where t2.start_date = t1.end_date
     and t2.row_no != t1.row_no )

子查询的限定使记录 3 无法满足自己。这可能不是完整的解决方案。如果您有多个具有相同开始和结束日期的记录,那么您最终可能无法识别某些记录。在这种情况下,ROW_NO 的可靠性很重要。

如果您可以保证对于任何给定的记录对,较高的 ROW_NO 始终表示按时间顺序较晚的记录,那么修复很简单:

     where t2.start_date = t1.end_date
     and t2.row_no > t1.row_no )

在某些情况下,可能无法提供此保证;这取决于如何分配 ROW_NO。但是这里已经有一些假设,除非你提供更多细节,否则我不会讨论它们。

UPDATE 语句比较棘手。

于 2013-06-24T08:31:40.080 回答
1

您可以使用该lag函数来引用前一行的值(定义“上一个”的含义作为查询的一部分;我假设您的“行号”是一个伪列,而不是您可以订购的实际列,并且您希望它们按开始日期顺序排列):

select start_date, end_date,
  case
    when lag_end_date is null then start_date
    when lag_end_date = start_date then start_date
    else lag_end_date
  end as adj_start_date
from (
  select start_date, end_date,
    lag(end_date) over (order by start_date, end_date) as lag_end_date
  from <your_table>
)

SQL 小提琴)。

的第一个when子句case处理“第一”行,最早的开始日期;因为没有前一行,lag所以将是null

start_date然后,您可以过滤结果以获取那些adj_start_date不匹配的结果。(另一个 SQL 小提琴)。

您可以在 a 中使用相同类型的构造merge来进行更新:

merge into <your table>
using (
  select r_id, start_date, end_date,
    case when lag_end_date is null then null
      when lag_end_date = start_date then null
      else lag_end_date
    end as adj_start_date
  from (
    select rowid as r_id, start_date, end_date,
      lag(end_date) over (order by start_date, end_date) as lag_end_date
    from t42
  )
) t
on (your_table>.rowid = t.r_id and t.adj_start_date is not null)
when matched then
update set <your table>.start_date = t.adj_start_date;

SQL 小提琴)。

于 2013-06-24T08:55:10.597 回答