• Not 100% sure I understand what you are trying to do, but I'm assuming your orders always have either one line or two.

    Not one of the cleverest solutions I've ever constructed, but here it is.

    WITH OneRowOrders AS

    (

    SELECT OrderID, ProjectID, ProductID, ProjectAmt, ID=MIN(ID)

    FROM #Orders

    GROUP BY OrderID, ProjectID, ProductID, ProjectAmt

    HAVING COUNT(*) = 1

    )

    SELECT ID, OrderID, ProjectID, ProductID, ProjectAmt

    ,ProductAmt = ISNULL(ProductAmt +

    LEAD(ProductAmt, 1) OVER

    (

    PARTITION BY OrderID, ProjectID, ProductID, ProjectAmt

    ORDER BY ID, rn

    ), 0)

    FROM

    (

    SELECT ID, OrderID, ProjectID, ProductID, ProjectAmt, ProductAmt

    ,rn=ROW_NUMBER() OVER (PARTITION BY OrderID, ProjectID, ProductID, ProjectAmt ORDER BY ID)

    FROM #Orders

    UNION ALL

    SELECT ID, OrderID, ProjectID, ProductID, ProjectAmt, 0, 2

    FROM OneRowOrders

    ) a

    ORDER BY ID, rn;

    It does assume that if you are posting in a SQL 2012 forum you are running on SQL 2012.

    Edit: Fixed indentation.


    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