I am doing a simple exercise that given a Mission view i have to recalculate the data on new insertions to do this i need to make a trigger this is what i have done at the moment:
CREATE VIEW Missioni AS
SELECT d.Codice, SUM(v.Chilometri) AS KmTotali, SUM(v.Chilometri) * a.CostoKm AS CostoTotale
FROM Dipendente d join Viaggio v on v.Dipendente = d.Codice join Auto a on a.Targa = v.Auto
GROUP BY d.Codice, a.CostoKm;
CREATE OR REPLACE FUNCTION CALCULATE_MISSION()
RETURNS trigger AS $CALCULATE_MISSION$
BEGIN
DELETE FROM Missioni;
INSERT INTO Missioni SELECT Dipendente, SUM(Chilometri), SUM(Chilometri * CostoKm) FROM Viaggio v JOIN AUTO a ON a.targa = v.auto GROUP BY Dipendente;
END;
$CALCULATE_MISSION$ LANGUAGE plpgsql;
CREATE TRIGGER CalcolaVistaOneShot AFTER INSERT ON Viaggio
FOR EACH STATEMENT
EXECUTE FUNCTION CALCULATE_MISSION();
At the moment I am doing this on pgAdmin 4 in the query editor and it is giving me the following error:
ERROR: it is not possible to delete from the "missions" view DETAIL: Views containing GROUP BY are not auto-updatable. HINT: To allow deletions from the view, either an INSTEAD OF DELETE trigger or an ON DELETE DO INSTEAD rule without conditions must be provided. CONTEXT: SQL statement "DELETE FROM Missions" PL / pgSQL calculate_mission () function line 3 to SQL statement
BEGIN?WHERE Viaggio v JOIN Auto a ON a.Targa = v.AutoDECLAREsection, there your variables ( NewKmTotali and NewCostoTotale) are declared.