SQL trigger function to UPDATE daily moving average upon INSERT

前端 未结 2 620
死守一世寂寞
死守一世寂寞 2021-01-25 23:24

I am trying to create a SQL trigger function which should UPDATE a column when data is INSERTed INTO the table. The update is based on the values present in the values being INS

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-25 23:45

    You may do an UPDATE FROM your select query using appropriate joins in your Trigger.

    create or replace function update_sma8() RETURNS TRIGGER AS
    $$
     BEGIN
    
    UPDATE daily_ohlc d SET sma8 = s.simple_mov_avg 
    FROM
    (
     SELECT  sec.cdate,AVG(sec.close)  
       OVER(ORDER BY sec.cdate ROWS BETWEEN 7 PRECEDING AND CURRENT ROW) AS 
        simple_mov_avg FROM daily_ohlc sec
    )s where s.cdate = NEW.cdate  --The newly inserted cdate
         AND d.cdate = s.cdate;   
    RETURN NULL;
    
    END $$ language plpgsql;
    

    Demo

    The only caveat of using this method is that if someone deletes a row or updates close column, then the values have to be recalculated, which won't happen for existing rows. Only the inserted row will see the right re-calculated value.

    Instead, you may simply create View to calculate the sma8 column from the main table for all rows when requested.

提交回复
热议问题