Count and Sum from 2 tables at the same time
432181Nov 3 2004 — edited Nov 3 2004Hi
I have encountered a SQL problem which I hope somebody can help me with. I have simplified the problem to make it less confusing.
I have a table A and a table B
Table A has the following columns
A_ID (Primary key)
DESCRIPTION
TYPE
HOURS
Table B has the following columns
B_ID (Primary key)
DESCRIPTION
HOURS
A_ID (Foreign Key to table A)
Then to the problem, I want to find the number of rows (COUNT(A_ID)) and SUM of HOURS in A where TYPE = a certain value, so far so well with the following QUERY:
SELECT NVL(COUNT(A.A_ID),0), NVL(SUM(A.HOURS),0)
FROM A
WHERE A.TYPE = 'value';
Then in addition to this I want a the sum of HOURS from table B where the foreign key B.A_ID = A.A_ID for all of the A_ID's that is of that certain TYPE. When I try the query below the COUNT goes from counting rows in table A to counting rows in table B, even though I explisitly ask it to count A.A_ID.
SELECT NVL(COUNT(A.A_ID),0), NVL(SUM(A.HOURS),0), NVL(SUM(B.HOURS),0)
FROM A , B
WHERE A.TYPE = 'value' AND B.A_ID = A.A_ID;
(I assume that the SUM(A.HOURS) may return the wrong result aswell, but due to certain circumstances I am not allowed to register test data that gives me any other value than zero at the moment, therefore I am not sure wheter or not that one gives a correct result when I add table B to the query.)
So for example with the following data:
Table A
A_ID - DESCRIPTION - TYPE - HOURS
1 - 'Description' - 'X' - 2
2 - 'Description' - 'X' - 1
3 - 'Description' - 'X' - 2
4 - 'Description' - 'Y' - 1
Say that I want to count the number of rows where type = 'X' and sum the hours for these rows
The correct result would be:
Count(A.A_ID): 3 (ID's 1, 2 and 3)
Sum(A.HOURS) : 5 (2+1+2)
Then I also want the sum of hours from B where the foreign key equals the primary key in one of the rows that I have counted from table A (in other words where B.A_ID = 1 or 2 or 3)
Given the following table B
B_ID - DESCRIPTION - HOURS - A_ID
1 - 'Description' - 1 - 1
2 - 'Description' - 2 - 1
3 - 'Description' - 1 - 2
4 - 'Description' - 2 - 2
5 - 'Description' - 1 - 3
6 - 'Description' - 2 - 3
7 - 'Description' - 1 - 4
8 - 'Description' - 2 - 4
9 - 'Description' - 1 - 4
That should give the following result:
Count(A.A_ID): 3 (ID's 1, 2 and 3)
Sum(A.HOURS) : 5 (2+1+2)
Sum(B.HOURS) : 9 (1+2+1+2+1+2)
Does anyone have a good solution? I can break it up into more than one select statement and I can create views if that helps, but at the moment I haven't quite figured a solution by doing that eighter.