-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 に答える