更新第一个匹配行

时间:2013-07-20 08:58:31

标签: sql postgresql postgresql-9.1

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

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 

添加限制不是leggal。

最后,只有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);

1 个答案:

答案 0 :(得分:1)

SQL Fiddle

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