• Or maybe it would be best to just skip all of that insufferable reading and do it like this.

    WITH SampleData (ID, Amount, Months) AS

    (

    SELECT 1, 143.23, 2 UNION ALL SELECT 2, 143.25, 6

    ),

    Tally (n) AS

    (

    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))

    FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)

    )

    SELECT ID, Amount, Months, n, DividedAmt, TotalAmt

    ,CorrectedAmt=DividedAmt +

    CASE WHEN ABS((TotalAmt-Amount)*100) <= n-1

    THEN 0

    ELSE .01*SIGN((TotalAmt-Amount))

    END

    FROM

    (

    SELECT ID, Amount, Months, n, DividedAmt

    ,TotalAmt=SUM(DividedAmt) OVER (PARTITION BY ID)

    FROM

    (

    SELECT ID, Amount, Months, n

    ,DividedAmt=CAST(Amount/Months AS DECIMAL(10,2))

    FROM SampleData a

    CROSS APPLY

    (

    SELECT TOP (Months) n

    FROM Tally

    ORDER BY n

    ) b

    ) a

    ) a;

    Note that most of the work (in fact both of the CTEs and the CROSS APPLY of the inner query, is just setting up the data/exploding the rows.

    Edit: Looking back I see that this solution is quite similar to Luisi's. Should have looked before I leaped.


    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