0
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;

enter image description here

Is it possible to calculate sum(b.value) as 9 instead of 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.

whsv26
  • 63
  • 1
  • 6

1 Answers1

0

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

See running example in DB Fiddle.

The Impaler
  • 45,731
  • 9
  • 39
  • 76