Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to query from two tables (sum up field values)

Author  Topic 

cy163
Starting Member

2 Posts

Posted - 2008-10-09 : 01:45:04




I have two tables tb1 and tb2. I would like to sum up field values from two tables. How to do this using a SQL statement.

tb1
Name Salary
Bob 1000
Tom 2000
John 3000
Winson 4000

tb2
Name Bonus
Bob 100
Tom 200


I would like to get the following result
Name Total
Bob 1100
Tom 2200
John 3000
Winson 4000

I have tried with the following statement but no luck.


SELEC tb1.Name, SUM(tb1.Salary + tb2.Bonus) Total From tb1, tb2 WHERE tb1.Name = tb2.Name group by tb1.Name order by Total

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-10-09 : 01:51:02
[code]SELECT t.Name,SUM(t.Salary)
FROM
(
SELECT Name,Salary
FROM tb1

UNION ALL

SELECT Name,Bonus
FROM tb2
)t
GROUP BY t.Name[/code]
Go to Top of Page
   

- Advertisement -