Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

TSQL Previous vs Current Record Flag

$
0
0

Hi All,

I have two tables

Table 1			
SEnrolmentID	ActiveFlag	FromDate	ToDate
1111	N	20/05/2014	21/05/2014
1111	N	21/05/2014	22/05/2014
1111	Y	22/05/2014	31/12/9998
Table 2				
SEnrolmentID	StatusKey	ActiveFlag	FromDate	ToDate
1111	1	Y	20/05/2014	31/12/9998
1111	8	Y	21/05/2014	31/12/9998
1111	1	Y	22/05/2014	31/12/9998

Need to create a new field called DeletedFlag where if the StatusKey = 8 then the previous records will have a flag = 1 else 0.

Target					
SEnrolmentID	ActiveFlag	FromDate	ToDate	StatusKey	DeletedFlag
1111	N	20/05/2014	21/05/2014	1	1
1111	N	21/05/2014	22/05/2014	8	1
1111	Y	22/05/2014	31/12/9998	1	0

How can I do that?

Create Table #Table1 (
	SEnrolmentID NvarChar(20),
	ActiveFlag Char(1),
	FromDate DateTime,
	ToDate DateTime
)
Insert Into #Table1 (SEnrolmentID, ActiveFlag, FromDate, ToDate)
Values 
('1111', 'N', '2014-05-13 13:40:26.673', '2014-05-13 13:40:26.687'),
('1111', 'N', '2014-05-13 13:40:26.680', '2014-05-13 13:40:26.690'),
('1111', 'Y', '2014-05-13 13:40:26.693', '9998-12-31 00:00:00.000')

Create Table #Table2 (
	SEnrolmentID NvarChar(20),
	StatusKey Int,
	ActiveFlag Char(1),
	FromDate DateTime,
	ToDate DateTime
)
Insert Into #Table2 (SEnrolmentID, StatusKey, ActiveFlag, FromDate, ToDate)
Values 
('1111', 1 ,'Y', '2014-05-13 13:40:26.673', '9998-12-31 00:00:00.000'),
('1111', 8 ,'Y', '2014-05-13 13:40:26.680', '9998-12-31 00:00:00.000'),
('1111', 1 ,'Y', '2014-05-13 13:40:26.693', '9998-12-31 00:00:00.000')


Select 
	a.*, b.StatusKey, Case When b.FromDate <> '9998-12-31'  Then 1 Else 0 End As DeletedFlag
From #Table1 a
Join #Table2 b 
	On a.SEnrolmentID = b.SEnrolmentID 
	and a.ActiveFlag = 'Y




Viewing all articles
Browse latest Browse all 23857

Trending Articles