【问题标题】:Discontinuous records, missing time gaps.不连续的记录,缺少时间间隔。
【发布时间】:2016-08-02 12:29:36
【问题描述】:

我有一个表Item_X,它的主列为Item_id,Country,Date_from。 不属于PK 的其他列是Date_ToTypeOfSale。 有TypeOfSale 1、2、3。

在特定时间段内,仅对销售类型有效。 例如:-

Date From 始终为 Date_to + 1。

我的表中有一些不连续的记录。 例子:-

2 月 1 日至 2 月 29 日的记录丢失。

我想找出所有此类记录。 不应考虑第一条记录,最后一条记录的 To_date 可以为空。

【问题讨论】:

  • 您是否有一列可以确定这些销售记录的订单
  • @AJ- 间隔应该是日历月,还是只是您的样本输入中的巧合?如果缺少连续三个月,您需要输出中的三行还是只需要一行(例如,显示 2015 年 10 月 1 日和 2015 年 12 月 31 日)?另外,开始和结束日期总体是什么?还是您只需要现有行之间的间隙,而不需要第一行之前或最后一行之后的间隙?日期列是字符数据类型还是实际日期数据类型?
  • 或者...等等...您是否要求显示表格中的现有行,哪里有空白?您究竟需要输出是什么样的?
  • 它们需要是日期,如果连续三个月缺失,那么我需要下一个/上一个记录,如果缺少某些日期,那么还需要下一个/上一个记录。第一条记录不应考虑,最后一条记录在 To_Date 中可以为空,也不应考虑。

标签: sql database oracle plsql


【解决方案1】:

这是一种方法:

select r.*
from records r
where not exists (select 1 from records r2 where r2.item_id = r.item_id and r2.date_from = r.date_to + 1) and
      exists (select 1 from records r2 where r2.item_id = r.item_id and r2.date_from > r.date_to);

这将返回间隙之前的第一条记录。

另一种方法使用lead()lag()

select r.*
from (select r.*,
             lead(date_from) over (partition by item_id order by date_from) as next_date_from,
             lag(date_to) over (partition by item_id order by date_from) as prev_date_to
      from records r
     ) r
where (date_from <> prev_date_to + 1) or
      (date_to <> next_date_from - 1);

这会返回两条记录。

【讨论】:

  • 还应检查国家/地区,不应考虑第一条记录,To_date 中最后一条记录可以为空
猜你喜欢
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多