課題は、前の日付を取得することです。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 日未満のものを除外するだけです。