• Last time I checked my statistics book SUM/COUNT = AVG, so allowing for the fact that some IDs may not exist in one table or the other, I will propose this:

    DECLARE @table1 TABLE (id INT, a INT)

    DECLARE @table2 TABLE (id INT, b INT)

    INSERT INTO @table1

    SELECT 1,6 UNION ALL SELECT 2,7 UNION ALL SELECT 3,8 UNION ALL SELECT 4,9

    INSERT INTO @table2

    SELECT 1,1 UNION ALL SELECT 2,2 UNION ALL SELECT 3,3 UNION ALL SELECT 5,4

    SELECT CASE WHEN a.id IS NULL THEN b.id ELSE a.id END

    ,CASE WHEN AVG(a) IS NULL THEN 0 ELSE AVG(a) END -

    CASE WHEN AVG(b) IS NULL THEN 0 ELSE AVG(b) END

    FROM @table1 a

    FULL OUTER JOIN @table2 b ON a.id = b.id

    GROUP BY CASE WHEN a.id IS NULL THEN b.id ELSE a.id END


    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