私はテーブル顧客履歴ログ顧客IDとmodification_dateを持っています。 CUSTOMER_IDが変更されていないがをCUSTOMER_ID Iを見つけることができるテーブル にエントリ(= last_date_with_no_modification)が存在しない改変されていない場合。私は日付が見つからないときを探す(=ギャップと諸島の問題)。同じクエリでギャップ日付と最小日付を見つけるにはどうすればいいですか?
しかし、同じクエリには日付が値が欠落していない場合last_date_with_no_modificationが CUSTOMER_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を取得する方法?これは動作するはずです
感謝。 – ema
あなたは大歓迎です!それが効いている場合、正しい答えを記入してください。 –