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
 joins in multiple tables

Author  Topic 

king_fisher
Starting Member

13 Posts

Posted - 2013-12-07 : 06:58:34
TAble 1:

id amount
1 100
2 200
3 300
4 400


Table 2:


id amount
1 100
1 100
2 200
3 300
4 null


Table 3:

id amount
1 null
2 200
2 200
3 300
3 200
4 null


id is common for each tables , how can i get output like this:
Collapse | Copy Code

id t1 t2 t3
1 100 200 null
2 200 200 200
3 300 300 500
4 400 null null

i m stuck with this query .


vijay nelson

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-12-07 : 08:29:38
[code]
SELECT t1.id,t1.TotalAmount,t2.TotalAmount,t3.TotalAmount
FROM (SELECT id,SUM(amount) AS TotalAmt
FROM Table1
GROUP BY id
)t1
INNER JOIN (SELECT id,SUM(amount) AS TotalAmt
FROM Table2
GROUP BY id
)t2
ON t2.id = t1.id
INNER JOIN (SELECT id,SUM(amount) AS TotalAmt
FROM Table3
GROUP BY id
)t3
ON t3.id = t1.id
[/code]

If all tables doesnt have all id values then use FULL JOIN rather than INNER JOIN

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -