Re: [postgresql-it] trigger update e sum function

  • From: Enzo Cocca <enzo.ccc@xxxxxxxxx>
  • To: romanelli.stefano@xxxxxxxxx, postgresql-it@xxxxxxxxxxxxx
  • Date: Mon, 30 Jun 2014 18:08:09 +0200

ciao stefano,

grazie veramente mille vedo che ti sei proprio impegnato :D

guardando un pò in giro ho provato a riassumere con questa istruzione che
mi funziona
(e vorrei un consiglio da te se come procedura va bene)

select sito,quadrato
  sum(case when specie = 'bos' then 1 else 0 end) bos,
  sum(case when specie = 'cervo' then 1 else 0 end) cervo,
  sum(case when specie = 'cane' then 1 else 0 end) cane,
  sum(case when specie = 'volpe' then 1 else 0 end) volpe
from fauna
group by sito,quadrato order by 1;
 la tabella che ho è quella che mi attendo

ora questa istruzione la metto in un trigger function tipo

CREATE OR REPLACE FUNCTION aggiorna()
  RETURNS trigger AS $aggiorna$
begin
insert into specie
select sito,quadrato,
  sum(case when specie = 'bos' then 1 else 0 end) bos,
  sum(case when specie = 'cervo' then 1 else 0 end) cervo,
  sum(case when specie = 'cane' then 1 else 0 end) cane,
  sum(case when specie = 'volpe' then 1 else 0 end) volpe

from fauna
group by sito,quadrato order by 1;
return null;
end;
$aggiorna$ LANGUAGE plpgsql VOLATILE;

CREATE TRIGGER aggiorna
  BEFORE INSERT OR UPDATE OR DELETE
  ON fauna
  FOR EACH ROW
  EXECUTE PROCEDURE aggiorna();

ora funzionerebbe tutto se non ci fossero le chivi primarie nella tab
specie  ma se non ci fossero creerei solo ridondanze duplicati.

ora sto cercando di capire come come aggiornare e inserire senza avere
problemi.

qualche consiglio?

enzo
-- 
Enzo Cocca (PhD Candidate)
Research Fellow
Università di Napoli "L'Orientale"
mail: enzo.ccc@xxxxxxxxx
cell: +393495087014

Other related posts: