同一行中2个值的总和

时间:2018-10-08 11:15:51

标签: postgresql sum

我是Postgresql 9.3的新手,我发现自己在一个简单的操作中遇到了麻烦。我必须使用触发器来执行两列的数值之和并将结果写入第三列。这是我的起始桌:

CREATE TABLE pratica
(
  progressivo text NOT NULL DEFAULT nextval('pratica_prog_seq'::regclass),
  sal1_importo_arc numeric(10,2),
  sal1_spese numeric(10,2),
  sal1_totale numeric(10,2),
   note text,
  CONSTRAINT pratica_pkey PRIMARY KEY (progressivo)
)
WITH (
  OIDS=FALSE
);

这是函数和触发器:

CREATE OR REPLACE FUNCTION sum_sal1()
RETURNS trigger AS
$$
BEGIN
IF NEW.sal1_importo_arc IS NULL
THEN
UPDATE pratica
SET sal1_totale = NEW.sal1_spese
WHERE pratica.sal1_totale IS DISTINCT FROM pratica.sal1_spese;
ELSE IF NEW.sal1_spese  IS NULL
THEN
UPDATE pratica
SET sal1_totale = NEW.sal1_importo_arc
WHERE pratica.sal1_totale IS DISTINCT FROM pratica.sal1_importo_arc;
ELSE
UPDATE pratica
SET sal1_totale = (SELECT (NEW.sal1_importo_arc + NEW.sal1_spese))
WHERE pratica.sal1_totale IS DISTINCT FROM (SELECT (pratica.sal1_importo_arc + pratica.sal1_spese));
END IF;
END IF;
RETURN NULL;
END
$$
  LANGUAGE plpgsql VOLATILE

CREATE TRIGGER sum_sal1
  AFTER INSERT OR UPDATE OF sal1_importo_arc
  ON pratica
  FOR EACH ROW
  EXECUTE PROCEDURE sum_sal1();

sal1_spesesal1_importo_arc可能包含NULL值,因此我提出了适当的条件。 问题在于,触发触发器时,它将使用修改后的行的相同值更新整个表的列sal1_total,而不仅仅是更改对象的行。 我怎么了 谢谢

1 个答案:

答案 0 :(得分:0)

在可能包含NULL的表达式中使用COALESCE()

每次计算值时都没有理由更新表,因为您可以通过以下简单方式使用触发器BEFORE

CREATE OR REPLACE FUNCTION sum_sal1()
RETURNS trigger AS
$$
BEGIN
    NEW.sal1_totale = COALESCE(NEW.sal1_importo_arc, 0) + COALESCE(NEW.sal1_spese, 0);
    RETURN NEW;
END
$$
  LANGUAGE plpgsql VOLATILE;

CREATE TRIGGER sum_sal1
  BEFORE INSERT OR UPDATE
  ON pratica
  FOR EACH ROW
  EXECUTE PROCEDURE sum_sal1();