挑战在于获得前一个日期。在 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 天的任何内容。