• If that still wasn't fast enough, this one should blow the doors off of both.

    SELECT a.[Contract], a.AdmissionDate, Cost=SumofCost, Members=CountofMembers

    ,SumofCost=CAST(0.0 AS DECIMAL(19,4))

    ,CountofMembers=0

    ,AvgCost=CAST(0.0 AS DECIMAL(19,4))

    INTO #NewTable

    FROM Members a

    JOIN Admission b ON a.[Contract] = b.[Contract] AND

    a.AdmissionDate = b.AdmissionDate

    ALTER TABLE #NewTable ALTER COLUMN AdmissionDate VARCHAR(6) NOT NULL;

    ALTER TABLE #NewTable ADD PRIMARY KEY(AdmissionDate);

    DECLARE @Lag1SOC DECIMAL(19, 4) = 0

    ,@Lag2SOC DECIMAL(19, 4) = 0

    ,@Lag3SOC DECIMAL(19, 4) = 0

    ,@Lag1CM INT = 0

    ,@Lag2CM INT = 0

    ,@Lag3CM INT = 0

    ,@rtSOC DECIMAL(19, 4) = 0

    ,@rtCM INT = 0

    ,@rn INT = 0;

    UPDATE #NewTable WITH(TABLOCKX)

    SET @rtSOC = SumOfCost = @rtSOC + Cost - @Lag3SOC

    ,@rtCM = CountOfMembers = @rtCM + Members - @Lag3CM

    ,AvgCost = CASE WHEN @rn < 3 THEN NULL

    WHEN @rtCM = 0 THEN 0

    ELSE @rtSOC / @rtCM

    END

    ,@Lag3SOC = @Lag2SOC

    ,@Lag2SOC = @Lag1SOC

    ,@Lag1SOC = Cost

    ,@Lag3CM = @Lag2CM

    ,@Lag2CM = @Lag1CM

    ,@Lag1CM = Members

    ,@rn = @rn + 1

    OPTION (MAXDOP 1);

    SELECT [Contract], AdmissionDate, SumofCost, CountofMembers, AvgCost

    FROM #NewTable;

    GO

    DROP TABLE #NewTable;

    Understanding how the Quirky Update (QU) works and all the rules can be a bit of a challenge, but this article by SQL MVP Jeff Moden goes into all the details:

    Solving the Running Total and Ordinal Rank Problems[/url]

    While the article covers only running totals, what I've done here is to limit the running totals to the current + prior 2 rows using the @lag variables.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St