|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| ||||||||||||||||||||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
3 tables 2 sums query?
Hi All,
My brain is hurting..Please help!!! I have 3 tables: Table A ID Username Table B ParentID SomeNumber Table C ParentID SomeNumber I need something like this (The totals of SomeNumber from both tables B and C for a given user in A): select a.username, sum(b.SomeNumber), sum(c.SomeNumber) from A, B, C where A.ID = B.ParentID and A.ID = C.ParentID group by a.ID Any help would be appreciated!!!! Thanks!! |
|
#2
|
||||
|
||||
|
do you get any errors message?
wrong result? you have to give some more information about you problem. what if you group by a.username instead of group by a.ID? |
|
#3
|
|||
|
|||
|
Quote:
When I use a.username the query executes but there are no results. I know for sure there is data present. |
|
#4
|
|||
|
|||
|
Quote:
SNAP!!! If either of the tables is empty, I get no results. I need to outer join the two child tables right? What does that look like? |
|
#5
|
|||
|
|||
|
Code:
select username,
(select sum(someNumber)
from b
where b.parentid = a.id),
(select sum(SomeNumber)
from c
where c.parentid = a.id)
from A
|
|
#6
|
|||
|
|||
|
Quote:
Thanks guys!! Here's what I ended up with. Any real difference? Performance? select a.username, sum(b.SomeNumber), sum(c.SomeNumber) from a left outer join b on (a.id = b.parentid) left outer join c on (a.id = c.parentid) group by username |
|
#7
|
|||
|
|||
|
The queries will give different results in some cases.
You can test with this data Code:
create table a(id int,username varchar(20)); insert into a values(1,'swampBoogie'); create table b(parentId int,somenumber int); insert into b values(1,47); insert into b values(1,11); create table c(parentId int,somenumber int); insert into c values(1,4711); |
|
#8
|
|||
|
|||
|
Quote:
Welp, I just got back to this and you're RIGHT! But now I have another problem.... I need want the totals by username (i.e. group by username) but I'm getting multiple records back for a given user. I've tried a couple of different ways to group things but nothing works right. Thoughts? |
|
#9
|
|||
|
|||
|
I'm not sure I understand what you mean, but this would get the total for each user
Code:
select username,
coalesce((select sum(someNumber)
from b
where b.parentid = a.id),0) +
coalesce((select sum(SomeNumber)
from c
where c.parentid = a.id),0)
from a
If this is not what you need, give some sample data and the expected result. |
![]() |
| Viewing: Dev Shed Forums > Databases > PostgreSQL Help > 3 tables 2 sums query? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|