Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2003
    Posts
    32

    Unanswered: How to Sum and Group from union result

    I have union query as:
    SELECT A, B
    FROM X
    UNION ALL
    SELECT A,B
    FROM Y

    I want to further SUM(B), GROUP BY A of above union result.

    How can I do this in one query?

    Thanks,

  2. #2
    Join Date
    Dec 2005
    Posts
    273
    Try:


    SELECT A, SUM(B) FROM

    (
    SELECT A, B
    FROM X
    UNION ALL
    SELECT A,B
    FROM Y ) C

    GROUP BY A ;

  3. #3
    Join Date
    Sep 2003
    Posts
    32

    Thanks

    Thanks Thanks

  4. #4
    Join Date
    Dec 2007
    Location
    Richmond, VA
    Posts
    1,328
    Provided Answers: 5
    Sometimes for better performance you might want to do multiple sums as it will be less data stored in memory for the final sum. I have had pretty good success with this in the past. Such as:

    SELECT A, SUM(B) FROM

    (
    SELECT A, sum(B)
    FROM X
    GROUP BY A
    UNION ALL
    SELECT A,sum(B)
    FROM Y
    GROUP BY A) C

    GROUP BY A ;

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •