SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 joins in multiple tables
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

king_fisher
Starting Member

India
13 Posts

Posted - 12/07/2013 :  06:58:34  Show Profile  Reply with Quote
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

India
52325 Posts

Posted - 12/07/2013 :  08:29:38  Show Profile  Reply with Quote

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


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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.09 seconds. Powered By: Snitz Forums 2000