PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Funzione PostgreSQL per scorrere/agire su molte righe con stato

Bene, questo non è certo carino ma è funzionale:

select sum(amt) as session_val
from (
  select segment,
         max(segment) over() as max_segment,
         amt
  from (
    select sum(case when atype = 'SET' then 1 else 0 end)
               over(order by "order") as segment,
           amt
    from command
    where session = 2
  ) x
) x
where segment = max_segment

Tuttavia è abbastanza semplice in PL/pgsql:

create function session_val(session int) returns int stable strict
language plpgsql as $$
declare
  value int := 0;
  rec command%rowtype;
begin
  for rec in select * from command where command.session = session_val.session loop
    if rec.atype = 'SET' then
      value := rec.amt;
    elsif rec.atype = 'ADD' then
      value := value + rec.amt;
    end if;
  end loop;
  return value;
end $$;

Quindi fai la tua scelta, immagino.