2017-12-26 20 views
0

私はテーブル顧客履歴ログ顧客IDmodification_dateを持っています。 CUSTOMER_IDが変更されていないをCUSTOMER_ID Iを見つけることができるテーブル にエントリ(= last_date_with_no_modification)が存在しない改変されていない場合。私は日付が見つからないときを探す(=ギャップと諸島の問題)。同じクエリでギャップ日付と最小日付を見つけるにはどうすればいいですか?

しかし、同じクエリには日付が値が欠落していない場合last_date_with_no_modificationCUSTOMER_IDためDATEADD(DAY,-1,min(modification_date))でなければなりません。

SQLクエリでこの最後の条件を追加する方法がわかりません。

"Customer_history" テーブル

は、私は、次の表を使用し

customer_id modification_date 
1 2017-12-20 
1 2017-12-19 
1 2017-12-17 
2 2017-12-20 
2 2017-12-18 
2 2017-12-17 
2 2017-12-15 
3 2017-12-20 
3 2017-12-19 

"#tmp_calendar" テーブル:QETギャップ日に使用

date 
2017-12-15 
2017-12-16 
2017-12-17 
2017-12-18 
2017-12-19 
2017-12-20 

クエリ:

WITH CTE_GAP AS 
(SELECT ch.customer_id, 
    LAG(ch.modification_date) OVER(PARTITION BY ch.customer_id ORDER BY ch.modification_date) as GapStart, 
    ch.modification_date as GapEnd, 
    (DATEDIFF(DAY,LAG(ch.modification_date) OVER(PARTITION BY ch.customer_id ORDER BY ch.modification_date), ch.modification_date)-1) GapDays 
FROM customer_history ch ) 
SELECT cg.customer_id, 
    DATEADD(DAY,1,MAX(cg.GapStart)) as last_date_with_no_modification 
FROM CTE_GAP cg 
CROSS JOIN #tmp_calendar c 
WHERE cg.GapDays >0 
AND c.date BETWEEN DATEADD(DAY,1,cg.GapStart) AND DATEADD(DAY,-1,cg.GapEnd) 
GROUP BY cg.customer_id 

結果:

customer_id last_date_with_no_modification 
1 2017-12-18 
2 2017-12-19 
3 2017-12-19 (Row missing) 

3をCUSTOMER_IDを取得する方法?これは動作するはずです

答えて

0

何か:たくさんChris.Yourクエリがうまく機能している

WITH CTE_GAP 
AS 
(
    SELECT 
     ch.customer_id, 
     LAG(ch.modification_date) OVER(PARTITION BY ch.customer_id ORDER BY ch.modification_date) as GapStart, 
     ch.modification_date as GapEnd, 
     (DATEDIFF(DAY,LAG(ch.modification_date) OVER(PARTITION BY ch.customer_id ORDER BY ch.modification_date), ch.modification_date)-1) GapDays 
    FROM @customer_history ch 
) 

SELECT DISTINCT 
    C.customer_id 
    , ISNULL(LD.last_date_with_no_modification, LD_NO_GAP.last_date_with_no_modification) last_date_with_no_modification 
FROM 
    customer_history C 
    LEFT JOIN 
     (
      SELECT 
       cg.customer_id, 
       DATEADD(DAY, 1, MAX(cg.GapStart)) last_date_with_no_modification 
      FROM 
       CTE_GAP cg 
       CROSS JOIN #tmp_calendar c 
      WHERE 
       cg.GapDays >0 
       AND c.date BETWEEN DATEADD(DAY, 1, cg.GapStart) AND DATEADD(DAY, -1, cg.GapEnd) 
      GROUP BY cg.customer_id 
     ) LD 
    ON C.customer_id = LD.customer_id 
    LEFT JOIN 
     (
      SELECT 
       customer_id 
       , DATEADD(DAY, -1, MIN(modification_date)) last_date_with_no_modification 
      FROM customer_history 
      GROUP BY customer_id 
     ) LD_NO_GAP 
    ON C.customer_id = LD_NO_GAP.customer_id 
+0

感謝。 – ema

+0

あなたは大歓迎です!それが効いている場合、正しい答えを記入してください。 –

関連する問題