Data from 2 tables
DBAsupport.com Forums - Powered by vBulletin
Results 1 to 4 of 4

Thread: Data from 2 tables

  1. #1
    Join Date
    Feb 2010
    Posts
    6

    Data from 2 tables

    Hi,

    There are 2 tables Tab1 & Tab2 with the below data:

    Code:
    Tab1:
    
    Name	Cost
    A1	5
    B2	1
    A1	8
    C3	5
    A1	7
    A1	8
    A1	5
    B2	3
    B2	3
    C3	1
    
    Tab2:
    
    Name	Cost
    A1	15
    B2	11
    A1	18
    C3	15
    A1	17
    A1	18
    A1	15
    B2	13
    B2	13
    C3	11
    I need to get Sum of Cost from both tables for a Name, i.e. the output should be as below:

    Code:
    Name	SumCost
    A1	116
    B2	44
    C3	32
    For A1 = 116:
    "Sum of Cost from tab1 - 33" + "Sum of Cost from tab1 - 83"

    Please suggest.

  2. #2
    Join Date
    Nov 2000
    Location
    Pittsburgh, PA
    Posts
    3,999
    It seems like a simple enough query.
    What is the issue?

    Code:
    select name, sum(value)
      from ( select name, value
               from tab1
              union all
             select name, value
               from tab1 )
     group by name
     order by name;
    this space intentionally left blank

  3. #3
    Join Date
    Feb 2010
    Posts
    6
    Thank you, so much!!!

  4. #4
    Join Date
    Nov 2000
    Location
    Pittsburgh, PA
    Posts
    3,999
    Of course looking back, I see the classic cut paste error.
    Your welcome.

    Code:
    select name, sum(value)
      from ( select name, value
               from tab1
              union all
             select name, value
               from tab2 )
     group by name
     order by name;
    this space intentionally left blank

Posting Permissions

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



Click Here to Expand Forum to Full Width