A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Sorry for the delay, but below is a query. I will need to add quite a few caveats.
- Since you did not provide the expected results, I have not been able to verify that the result is correct.
- Building logic on a free-text column is precarious. Then again, from your small sample, it seems that the action_desc column is machine generated, so I'm taking my chances that the text is consistent. But you may have to refine that part.
- The solution requires SQL 2012 or later. (I note that you implement LAG in the style we had to do up to SQL 2008.)
DECLARE @T TABLE (type varchar(10) NOT NULL,
action nvarchar(50) NULL,
factor tinyint NOT NULL CHECK (factor IN (0, 1)),
final bit NOT NULL,
UNIQUE (type, action)
)
INSERT @T (type, action, factor, final)
VALUES('INIT', NULL, 1, 0),
('ST', 'Status changed from ''Open'' to ''Hold''', 1, 0),
('ST', 'Status changed from ''Hold'' to ''Open''', 0, 0),
('ST', 'Status changed from ''Open'' to ''Acknowledged''', 1, 1)
; WITH curandprev AS (
SELECT a.call_req_id, a.time_stamp, t.factor,
prevstamp = LAG(a.time_stamp) OVER(PARTITION BY a.call_req_id ORDER BY a.time_stamp),
analyst = CASE WHEN t.final = 1 THEN a.analyst END
FROM act_log a
JOIN @T t ON a.type = t.type
AND (convert(nvarchar(MAX), a.action_desc) = t.action OR t.action IS NULL)
), aggr AS (
SELECT call_req_id, MAX(analyst) AS analyst, SUM(factor \* (time_stamp - prevstamp)) AS totaltime
FROM curandprev
GROUP BY call_req_id
)
SELECT cr.ref_num, concat(ca.first_name, ' ', ca.last_name),
days = totaltime / 86400, hhmmss = dateadd(second, totaltime % 86400, convert(time(0), '00:00:00'))
FROM aggr a
JOIN call_req cr ON a.call_req_id = cr .persid
JOIN ca_contact ca ON a.analyst = ca.contact_uuid