Please any ideas on how I can achieve the result shown in the attached picture .For now I have all the rows of the error field initiated with a default value of '0' and update the field based on different conditions but for the result .Its a bit challenging since its based on comparing 2 rows. **The logic that allows episodes to be condensed into a single continuous care episode is a discharge code of 22 followed by an admission code of 4 on the same day. So if a discharged code of 22 is followed by a different code other than an admission code of 4 for the same day that is an invalid entry.
drop table #source
CREATE TABLE #source(patidid varchar(20),epn int,preadmitdate datetime,adminttime varchar(10),
admitcode varchar(10),admittype varchar(25),datedischarge datetime,disctime varchar(10),disccode varchar(10),dischargetype varchar(20),errorcode int)
INSERT INTO #source VALUES
(1849,1,'4/23/2020','7:29',1,'First Admission','7/31/2020','9:03',22,'Campus Transfer',0)
,(1849,2,'7/31/2020','11:00',4,'Campus Transfer','7/31/2020','12:09',22,'Campus Transfer',0)
,(1849,3,'7/31/2020','13:10',2,'Re-Admission',null,null,null,null,0)
select * from #source