I have 2 tables @Claims and @ClaimsActivity:
Query:
declare @Claims table (ClaimID int)
insert into @Claims
values (6070), (6080)
declare @ClaimsActivity table
(
Activityid int,
ClaimID int,
Activity int,
ActivityDate datetime,
ClaimStatus int
)
insert into @ClaimsActivity
values (1, 6070, 0, '2017-11-05 20:23:16.640', 0),
(3, 6070, 6, '2017-11-06 13:50:28.203', 0),
(4, 6070, 9, '2017-11-07 13:39:28.410', 0),
(5, 6070, 10, '2017-11-07 13:40:49.980', 0),
(7, 6070, 8, '2017-11-07 15:46:18.367', 1),
(8, 6070, 8, '2017-11-07 16:50:49.543', 1),
(9, 6070, 9, '2017-11-07 16:50:54.733', 0),
(10, 6070, 4, '2017-11-07 16:55:22.135', 0),
(11, 6070, 6, '2017-11-08 18:32:15.101', 0),
(12, 6080, 0, '2017-11-12 11:15:17.199', 0),
(13, 6080, 8, '2017-11-13 09:12:23.203', 1)
select *
from @Claims
select *
from @ClaimsActivity
order by ActivityDate
I need to add 2 columns based on data in @ClaimsActivity: IsReopened and DateReopened
The logic is:
- If the last
ClaimStatus(based on ActivityDate) = 1 thenIsReopened= 0 - But if the last
ClaimStatus= 0 then it need to go and check whether one of theActivityis =9(Claim Reopened) - and if one of the Activity = 9 then
IsReopenedshould = 1 andDateReopenedshould be the last date when it was reopened
I brought column StatusOfClaim, but I also need IsReopened and DateReopened
select
Claimid,
isnull((select top 1
case when al.ClaimStatus = 1
then 'Closed'
else 'Open'
end
from
@ClaimsActivity al
where
C.ClaimID = al.ClaimID
order by
al.ActivityDate desc), 'Open') as 'Status of Claim',
NULL as 'isReopen',
NULL as 'DateReopened'
from
@Claims c
Desired output should be like this:

