postgres 将不同的 table 列从多对一连接数据求和

postgres sum different table columns from many to one joined data

假设我有以下两个表:

foo:

| id | goober | value |
|----|--------|-------|
| 1  | a1     | 25    |
| 2  | a1     | 125   |
| 3  | b2     | 500   |

bar:

| id | foo_id | value |
|----|--------|-------|
| 1  | 1      |  4    |
| 2  | 3      |  19   |
| 3  | 3      |  42   |
| 4  | 3      |  22   |
| 5  | 3      |  56   |

注意 bar.foo_id : foo.id 的 n:1 关系。

我的目标是对表 foobarvalue 列求和,加入 bar.foo_id=foo.id,最后按 goober 来自 foo。然后在可能的情况下进行计算,但并不重要。

导致最终输出类似于:

| goober | foo_value_sum | bar_value_sum | foo_bar_diff |
|--------|---------------|---------------|--------------|
| a1     | 150           | 4             | 146          |
| b2     | 500           | 139           | 361          |

通过以下创建两个 CTE 然后将它们连接起来的查询应该相当简单:

with bar_agg as
(
    select foo.goober
    ,sum(bar.value) bar_value_sum
    from foo
    join bar
      on bar.foo_id = foo.id
    group by foo.goober
)
,foo_agg as 
(
    select foo.goober
    ,sum(foo.value) foo_value_sum
    from foo
    group by foo.goober
)
select foo.goober
,foo_value_sum
,bar_value_sum
,foo_value_sum - bar_value_sum foo_bar_diff
from foo_agg foo
left join bar_agg bar
  on bar.goober = foo.goober
order by foo.goober