-1

这是一些数据的示例

id  CurrentMailPromoDate
1   1/1/2013
2   3/1/2013
3   6/9/2013
4   6/10/2013
5   9/18/2013
6   12/27/2013
7   12/27/2013

我需要的是仅提取当前和上一个记录之间的日期差异> = 100的那些id

换句话说,结果集将是:

id  CurrentMailPromoDate    
1   1/1/2013      **initial record**
3   6/9/2013    
5   9/18/2013   
6   12/27/2013  
7   12/27/2013  
4

1 回答 1

1

挑战在于获得前一个日期。在 SQL Server 2012 中,您可以使用lag(),但在 SQL Server 2008 中不支持此功能。相反,我使用相关子查询来获取上一个日期。

以下返回您正在寻找的集合:

with t as (
      select 1 as id, CAST('2013-01-01' as DATE) as CurrentMailPromoDate union all
      select 2, '2013-03-01' union all
      select 3, '2013-06-09' union all
      select 4, '2013-06-10' union all
      select 5, '2013-09-18' union all
      select 6, '2013-12-27' union all
      select 7, '2013-12-27')
select t.id, t.CurrentMailPromoDate
from (select t.*,
             (select top 1 CurrentMailPromoDate
              from t t2
              where t2.CurrentMailPromoDate < t.CurrentMailPromoDate
              order by CurrentMailPromoDate desc
             ) as prevDate
      from t
     ) t
where DATEDIFF(dd, prevDate, CurrentMailPromoDate) >= 100 or prevDate is null;

编辑:

子查询返回每条记录的前一个日期。对于给定的记录,它正在查看小于记录日期的所有日期。这些按降序排序,并选择第一个。这是prevDate.

where子句仅过滤掉距前一个日期不到 100 天的任何内容。

于 2013-07-18T19:14:29.310 回答