|
Question : SQL SUM Across Tables
|
|
OK, I have to write a query to sum the values returned from multiple tables. The details are as follows:
TABLE A contains the field I would like to sum, lets call it NUMBER in TABLE A. TABLE B contains a set of classifications for records in TABLE A. The field in TABLE B is CLASSIFICATION and can have the following values: CLASS 1, CLASS 2 and CLASS 3. A single record in TABLE A can, and will, have many classifications in TABLE B. For example, a single record in TABLE A can be CLASS 1, CLASS 2 and CLASS 3 and any combination thereof.
I want to be able to sum the NUMBER field from TABLE A across records that have related records in TABLE B for CLASS 1, CLASS 2 and CLASS 3. Please note in the example, the record in TABLE A must have all three classes to be valid for the summation. If it only has CLASS 1 and CLASS 2, then it should not be included.
Assume a simplified data model as follows:
TABLE A - ID (unique identifier) - NUMBER
TABLE B - ID (relationship to TABLE A) - Classification
|
|
Answer : SQL SUM Across Tables
|
|
doh
select result = sum(a.number) from tableA a join (select ID from TableB where classification in ('CLASS 1','CLASS 2','CLASS 3') group by id having count(distinct classification) = 3) b on a.id = b.id
|
|
|
|