Updating summary row counts in one table from another

  • I've run into this a few times - I have TableA that has a very large volume of rows added to it and a summary TableB table that shows row counts from TableA. I get a TSQL error when I use COUNT and GROUP BY in an UPDATE statement so here's what I use:

    SELECT b.BatchID, b.UserID, COUNT(b.MessageID) ResultCount

    INTO #BatchCount

    FROM TableA a LEFT JOIN TableB b

    ON a.UserID = b.UserID AND a.BatchID = b.BatchID

    WHERE b.BatchID = 3

    GROUP BY a.BatchID, a.UserID

    UPDATE TableA SET ResultCount = bc.ResultCount

    FROM TableA a JOIN #BatchCount bc

    ON a.UserID = bc.UserID AND a.BatchID = bc.BatchID

    So, basically, create a summary table with row counts and then update the TableB with those counts. What's the right way to do this with a single UPDATE statement rather than using a temp table?

    Thanks!

    Mark

  • You need to do the count (or any aggregation) as a SubQuery and join to it for the update.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply