开发者

SQL sum() with multiple level joins

Let's say I have the following table relationships (via keys existing on both ends)

table a -> table b
table b -> table c
table c -> table d
table d -> table e
table e -> table f

And I want to group by a key on table a and sum() values from table f as if both tables were directly joined.

Problem is that if I do that, information will be duplicated as all relationships from a -> b -> c -> d -> e -> f will repeat (as Andomar said: some information repeats because there are multiple routes from A to F)

Is there a way around that, or is my only choice to create a middle table containing the table a -> table f relationship?

Details:开发者_如何学Go

Table a
id1 | id2

Table b
id2 | id3

Table c
id3 | value

select a.id1, sum(value) from a 
inner join b on a.id2 = b.id2
inner join c on b.id3 = c.id3
group by a.id1

Data example:

Doing the join, the relationship is:

a b c value
1 2 2 20
1 3 2 20
1 4 2 20

If I do the sum(), I will get 60 but I want to get 20

Thanks


I'm assuming that some information repeats because there are multiple routes from A to F. If there is a unique key in F, you can un-duplicate the routes using a subquery:

SELECT  SubQuery.AValue, sum(SubQuery.FValue)
FROM    (
        SELECT a.value as AValue, f.key, f.value as FValue
        FROM a
        INNER JOIN b ON b.key = a.key
        INNER JOIN c ON c.key = b.key
        INNER JOIN d ON d.key = c.key
        INNER JOIN e ON e.key = d.key
        INNER JOIN f ON f.key = e.key
        GROUP BY a.value, f.key, f.value
        ) as SubQuery
GROUP BY SubQuery.AValue

The subquery ensures each row in F is only counted once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜