There is no particular order to the Statuses
It can be N-COMP before it is SENT or vise versa.
Its, a matter of ordering by completeddate column until it hits the first completion date. Summarice the datediff and counts of the Statuses which happened in between.
Then again if there are any statuses following that completiondate.
That being said, it may still not make much sense to you but I am open to suggestions of what you think may be the best way to proceed, providing you get the gist of what I am trying to do.
I tried something like this, however it stops once it hits the Completed status and does not provide the summary past that.
Also it inst the most efficient with the OUTER APPLY
SELECT
Identifier
,RE_ACT_COMPLETION_TIME
,COUNT(CASE WHEN RE_ACT_COMPLETION_TIME < RE_ACT_NCO_TIME THEN 0 ELSE 1 END) AS [RE-AN NCO #]
,COMP_CompletedDate AS [Count_N-CO]
FROM
(
select identifier
,case
when sum(case when SN_STATUS='COMP' and SN_TYPE = 'Re-Activattion' then 1 else 0 end)>0
then str(datediff(day
,min(case
when SN_TYPE = 'Re-Activattion'
then CreatedDate
else null
end
)
,min(case
when (SN_TYPE = 'Re-Activattion'
and SN_STATUS='COMP'
)
then CompletedDate
else null
end
)
)
)
when sum(case when SN_TYPE='Re-Activattion' then 1 else 0 end)>0
then 'NOT COMP'
else 'NO RE-ACT'
end
as RE_ACT_COMPLETION_TIME
,case
when sum(case when SN_STATUS='COMP' and SN_TYPE = 'Re-Activattion' then 1 else 0 end)>0
then str(datediff(day
,min(case
when SN_TYPE = 'Re-Activattion'
then CreatedDate
else null
end
)
,min(case
when (SN_TYPE = 'Re-Activattion'
and SN_STATUS='N-CO'
)
then CreatedDate
else null
end
)
)
)
else '0'
end
as RE_ACT_NCO_TIME
,SUM(CASE WHEN t.CreatedDate <= OA.COMP_CompletedDate AND t.SN_Status ='N-CO' THEN 1 ELSE 0 END) AS COMP_CompletedDate
from #temp AS t
OUTER APPLY
(SELECT TOP(1) ot.CompletedDate AS COMP_CompletedDate
FROM #temp AS ot
WHERE
t.Identifier=ot.Identifier
AND ot.CreatedDate >= t.CreatedDate
AND ot.SN_TYPE = 'Re-Activattion'
AND ot.SN_STATUS='COMP'
ORDER BY ot.CompletedDate ASC
)OA
WHERE Identifier = '64074558792'
group by identifier
)A
GROUP BY
Identifier
,RE_ACT_COMPLETION_TIME
,COMP_CompletedDate