Ebrahim Ghasemi
Ebrahim Ghasemi

Reputation: 6126

Query the sum of some cells in a table based on an id in another table

Let assume that we have two tables named family_data and person_info as below:

# family_data
person_id | family_id
1              1
2              2
3              1
4              1
5              2

# person_info
person_id | weight
1             50
2             80
3             30 
4             60
5             40

How can I have a table which contains pairs of (family_id, sum_of_members_weight) as below:

# Query output:

family_id | total_weight
1              140
2              120

Upvotes: 0

Views: 22

Answers (1)

GMB
GMB

Reputation: 222582

You can join and aggregate:

select f.family_id, sum(p.weight) total_weight
from family_data f
inner join person_info p on p.person_id = f.person_id
group by f.family_id

Upvotes: 1

Related Questions