Friday, October 24, 2014

Compare dates between 2 different rows and columns


create table test (ROWID int, Customer_ID varchar(15), PART_ID varchar(15), Effective_Date datetime, Discontinue_Date datetime)

Insert into test values
(53, '00018','MCL001950','2012-01-17','2013-04-01')
, (54130, '00018','MCL001950','2013-04-02','2013-09-24')
, (65089, '00018','MCL001950','2013-09-25','2013-04-01')
, (48021, '20515','MCL001950','2013-01-17','2014-04-01')
, (58521, '20515','MCL001950','2014-04-02','2013-09-24')
, (72092, '20515','MCL001950','2012-09-25','2016-04-01')
, (64028, '36988','MCL001950','2014-05-28','2016-09-24')
, (73019, '36988','MCL001950','2014-09-25','2016-04-01')

;with mcyte as (
select *,Lead (Effective_Date) OVER (PARTITION BY Customer_ID,PART_ID ORDER BY Effective_Date ASC) Effective_Date_below
From test)

Select ROWID,Customer_ID ,PART_ID,Effective_Date, Discontinue_Date, Effective_Date_below from mcyte
WHERE datediff(day,Effective_Date,Effective_Date_below)<0


drop table test


No comments:

Post a Comment