SQL aggregation query, grouping by entries in junction table

Posted by cm007 on Stack Overflow See other posts from Stack Overflow or by cm007
Published on 2011-11-21T17:43:06Z Indexed on 2011/11/21 17:50 UTC
Read the original article Hit count: 232

I have TableA in a many-to-many relationship with TableC via TableB. That is,

TableA       TableB           TableC
id | val     fkeyA | fkeyC    id | data

I wish the do select sum(val) on TableA, grouping by the relationship(s) to TableC. Every entry in TableA has at least one relationship with TableC. For example,

TableA
1 | 25
2 | 30
3 | 50

TableB
1 | 1
1 | 2
2 | 1
2 | 2
2 | 3
3 | 1
3 | 2

should output

75
30

since rows 1 and 3 in Table have the same relationships to TableC, but row 2 in TableA has a different relationship to TableC.

How can I write a SQL query for this?

© Stack Overflow or respective owner

Related posts about sql

Related posts about sql-server