If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > DB2 > How to Sum and Group from union result

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 04-08-09, 09:55
newer newer is offline
Registered User
 
Join Date: Sep 2003
Posts: 32
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,
Reply With Quote
  #2 (permalink)  
Old 04-08-09, 09:59
umayer umayer is offline
Registered User
 
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 ;
Reply With Quote
  #3 (permalink)  
Old 04-08-09, 10:53
newer newer is offline
Registered User
 
Join Date: Sep 2003
Posts: 32
Thanks

Thanks Thanks
Reply With Quote
  #4 (permalink)  
Old 04-08-09, 12:01
dav1mo dav1mo is offline
Registered User
 
Join Date: Dec 2007
Location: Richmond, VA
Posts: 782
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 ;
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On