Postgres触发函数来更新另一个表中的聚合结果

时间:2017-12-24 04:47:08

标签: postgresql

我有两张桌子。表x和表y。表x每天更新。我希望在表x中插入新数据后立即更新表y。表y包含每天表x中所有更新的聚合值。 日期是日期类型,两列的其余部分是实际类型。 Table_x可以每天更新,table_y应该自动更新。

x

Date    Sales    product
12/12/2017   4000   2
12/12/2017   3000   1
12/12/2017   2000   1
12/12/2017   5000   3
11/12/2017   1000   3
11/12/2017   2000   4

y(如下所示更新):

Date   Sales   product
12/12/2017   14000   7
11/12/2017   3000    7

我编写了如下所示的触发器功能,但它更新了每个项目而不是聚合值。

CREATE OR REPLACE FUNCTION public.rec_insert_table_y()
RETURNS trigger AS
$BODY$  
BEGIN  
INSERT INTO table_y ("Date","Sales","product")
SELECT NEW."Date",(sum(NEW."Sales")),(sum(NEW."product"))
GROUP BY NEW."Date";
RETURN NEW;

触发功能:

CREATE TRIGGER insert_into_table_y
AFTER INSERT
ON public.table_x
FOR EACH ROW
EXECUTE PROCEDURE public.rec_insert_table_y();

1 个答案:

答案 0 :(得分:0)

如果存在,您可以编写更新聚合值的触发器,否则编写插入。

此外,您必须知道'x'表中的更新和删除:

create function y_x_trg() returns trigger
  language plpgsql
as
$body$
declare
  row_exists boolean;
begin
  if tg_op<>'INSERT' then
    update y 
      set sales = y.sales - old.sales,
          product = y.product - old.product
      where y.date = old.date
      returning true into row_exists;
  end if;
  if tg_op<>'DELETE' then
    update y 
      set sales = y.sales + new.sales,
          product = y.product + new.product
      where y.date = new.date
      returning true into row_exists;
    if row_exists is not true then
      insert into y values (new.date, new.sales, new.product);
    end if;
    return new;
  else
    return null;
  end if;
end;
$body$;

create trigger y_x_trg AFTER INSERT OR UPDATE OR DELETE ON x
    FOR EACH ROW EXECUTE PROCEDURE y_x_trg();

您可以在http://rextester.com/FVR79644

看到正在运行的示例