2

我需要根据表 A 聚合更新表 B。从表 A 聚合到表 B 的关系是 1:M ,但我只想更新 B 中的一个匹配行(它可以是“许多”中的任何行)。

update B set spent = aggregation.spent
from 
(select provider_id,sum(spent) spent from A group by provider_id) aggregation
where B.provider_id = aggregation.provider_id 

添加限制是不合法的。

最后,只有 B 中的一条匹配记录需要与更新后的花费一起使用。

CREATE TABLE A
(
  id bigserial NOT NULL,
  provider_id bigint,
  channel int,
  spent int
 );

CREATE TABLE B
(
  id bigserial NOT NULL,
  provider_id bigint,
  spent int
 );

insert into A values (1,1,1,1);
insert into A values (2,1,2,1);
insert into B values (1,1,0);
insert into B values (2,1,0);
4

1 回答 1

1

SQL小提琴

update B set spent = s.spent
from
    (
        select distinct on (provider_id)
            be.id, aggregation.spent
        from
            (
                select provider_id, sum(spent) spent
                from A
                group by provider_id
            ) aggregation
            inner join
            B be using (provider_id)
    ) s    
where B.id = s.id
于 2013-07-20T10:02:03.207 回答