• This is my best guess at doing this WITHOUT A CURSOR.

    I combined your two derived tables into one by using the LAG function and removed unnecessary conditions in your CASE expression.

    Insert into @tempRY (ryear, rmonth, tblclaimstatusactionID,tbllineID, tbllinestatusID, companyname, ronumber, line, cstatus, LastUpdatedBy, name, dStarted, Dfinsished, Duration_sec, RY)

    SELECT

    DATEPART(YYYY, derivedtbl_1.LastUpdatedOn) as Year,

    DATEPART(MM, derivedtbl_1.LastUpdatedOn) as Month,

    derivedtbl_1.tblclaimstatusactionID,

    derivedtbl_1.tbllineID,

    derivedtbl_1.tbllinestatusId,

    tblcustomer.companyname,

    tblro.ronumber,

    tblline.line,

    tbllinestatus.status,

    derivedtbl_1.LastUpdatedBy,

    .name,

    derivedtbl_1.prevLastUpdatedOn AS Started,

    derivedtbl_1.LastUpdatedOn as Finished,

    DATEDIFF(ss, derivedtbl_1.prevLastUpdatedOn, derivedtbl_1.LastupdatedOn) AS Duration_sec,

    CASE

    WHEN DATEDIFF(ss, derivedtbl_1.prevLastUpdatedOn, derivedtbl_1.LastupdatedOn) <= 899 Then 'OK'

    WHEN DATEDIFF(ss, derivedtbl_2.LastUpdatedOn, derivedtbl_1.LastupdatedOn) <=1199 Then 'Y'

    WHEN derivedtbl_1.tbllinestatusId <> 78 Then 'R'

    ELSE 'OK'

    END AS RY

    FROM

    (

    SELECT tblclaimstatusactionID, tbllineID, tbllinestatusId, LastUpdatedBy, LastUpdatedOn, LAG(LastUpdatedOn) OVER( PARTITION BY LastUpdatedBy ORDER BY LastUpdatedOn) prevLastUpdateOn

    FROM tblclaimstatusaction

    WHERE tbllinestatusId <> 23

    AND LastUpdatedOn > DATEADD(MONTH, -6, GETDATE())

    ) AS derivedtbl_1

    ON .tbluserID = derivedtbl_1.LastUpdatedBy

    INNER JOIN tbllinestatus

    ON derivedtbl_1.tbllinestatusId = tbllinestatus.tbllinestatusID

    INNER JOIN tblline

    ON derivedtbl_1.tbllineID = tblline.tbllineID

    INNER JOIN tblro

    ON tblline.tblroID = tblro.tblroID

    INNER JOIN tblcustomer

    ON tblro.tblcustomerID = tblcustomer.tblcustomerID

    Remember that CASE WHEN clauses are evaluated in order, so you don't have to test for things that can be ruled out by previous WHEN clauses. For instance your first test is whether the difference is <= 899. If that test fails, you know that the difference has to be >= 900, so you don't need to test for it.

    Drew

    J. Drew Allen
    Business Intelligence Analyst
    Philadelphia, PA