2016-08-02 71 views
0

我有一个表Item_X其主要列为Item_id,Country,Date_from。 其他列不是PK的一部分是Date_To,TypeOfSale。 有TypeOfSale作为1,2,3.不连续的记录,缺少时间差距。

在一个特定的时间段内只有在销售类型是有效的。 对于防爆: - enter image description here

日期从总是DATE_TO + 1

我在表中的一些记录,这是不连续的。 示例: - enter image description here

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

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

+0

您是否有一列确定这些销售记录的订单? –

+1

@ AJ-间隔应该是日历月,还是只是样本输入中的巧合?如果连续三个月缺失,您需要输出三行还是一行(例如,显示2015年10月1日和2015年12月31日)?另外,整体的开始和结束日期是什么?或者你只需​​要现有行之间的差距,而不是在第一行之前或之后?日期列是字符数据类型还是实际日期数据类型? – mathguy

+0

或......等等......你是否要求显示表格中现有的行,哪里存在差距?你究竟需要输出看起来像什么? – mathguy

回答

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); 

这将返回两个记录。

+0

还应该为国家进行检查,不应考虑第一条记录,并且最后一条记录可以在To_date中为null –