aggregate on multiple joins from one parent table

Thread Solved

Join Date: Nov 2007
Posts: 8
Reputation: AbuShokry is an unknown quantity at this point 
Solved Threads: 0
AbuShokry AbuShokry is offline Offline
Newbie Poster

aggregate on multiple joins from one parent table

 
0
  #1
Mar 17th, 2009
Hello all,

I'm having the following problem,

I have three tables, Person, Income, Outcome
Person has the primary key : ID
Income has two fields : PersonID [Foreign] and IncomeAmount
Outcome has two fields : PersonID [foreign] and OutcomeAmount


I need to make a query that gets the summation of IncomeAmount and the summation of OutcomeAmount for each personID

My Query which gets totally wrong data is:
SELECT Person.ID, Sum(Income.IncomeAmount) , Sum(Outcome.OutcomeAmount) 
From Person,Outcome,Income
Where Person.ID = Income.PersonID AND Person.ID = Outcome.PersonID
Group by Person.ID


Why does it gets wrong data?
what am I missing here ?

thanks
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 1,162
Reputation: dickersonka will become famous soon enough dickersonka will become famous soon enough 
Solved Threads: 138
dickersonka dickersonka is offline Offline
Veteran Poster

Re: aggregate on multiple joins from one parent table

 
0
  #2
Mar 17th, 2009
  1. SELECT p.ID,
  2. (SELECT SUM(i.IncomeAmount) FROM Income i WHERE i.PersonId = p.ID) AS INCOME_AMOUNT,
  3. (SELECT SUM(o.OutcomeAmount) FROM Outcome o WHERE o.PersonId = p.ID) AS OUTCOME_AMOUNT
  4. FROM Person p
Last edited by dickersonka; Mar 17th, 2009 at 4:36 pm.
Custom Application & Software Development
www.houseshark.net
Reply With Quote Quick reply to this message  
Join Date: Nov 2007
Posts: 8
Reputation: AbuShokry is an unknown quantity at this point 
Solved Threads: 0
AbuShokry AbuShokry is offline Offline
Newbie Poster

Re: aggregate on multiple joins from one parent table

 
0
  #3
Mar 18th, 2009
Ahaa, that's how I should do it.

Thank you very much man, it works perfectly
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:




Views: 698 | Replies: 2
Thread Tools Search this Thread



Tag cloud for MS SQL
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC