[英]How to calculate sum with multiple joins involved
with a as (
select
1 as id,
1 as value
),
b as (
select
1 as id,
1 as a_id,
1 as value
union all select 2, 1, 2
union all select 3, 1, 3
union all select 4, 1, 3
),
d as (
select
1 as id,
1 as b_id,
1 as value
union all select 2, 1, 2
union all select 3, 1, 3
)
select
a.id,
b.id,
b.value as b_value,
d.id
from a
left join b on a.id = b.a_id
left join d on b.id = d.b_id;
Is it possible to calculate sum(b.value)
as 9 instead of 11?是否可以将
sum(b.value)
计算为 9 而不是 11?
I've been trying to do it like this , but with no success.我一直在尝试这样做,但没有成功。
sum(b.value) * (count(distinct b.id)::decimal / count(*))
will give 7.3 instead of 9. sum(b.value) * (count(distinct b.id)::decimal / count(*))
将给出 7.3 而不是 9。
You can use a subquery to identify duplicate rows.您可以使用子查询来识别重复的行。 Then the aggregation is simple.
然后聚合很简单。 For example:
例如:
with a as (
select
1 as id,
1 as value
),
b as (
select
1 as id,
1 as a_id,
1 as value
union all select 2, 1, 2
union all select 3, 1, 3
union all select 4, 1, 3
),
d as (
select
1 as id,
1 as b_id,
1 as value
union all select 2, 1, 2
union all select 3, 1, 3
)
select sum(col1)
from (
select b.id, max(b.value) as col1
from a
left join b on a.id = b.a_id
left join d on b.id = d.b_id
group by b.id
) x
Result:结果:
9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.