Para excluir das linhas de cálculo anteriores ao último
Total você pode usar a chave primária em uma consulta acessória. Declare nova variável v_fnserial .Encontre um fnserial da linha com a última ocorrência de 'Total' para determinado pcnum e fnname e atribua o valor a v_fnserial .Na consulta principal adicione uma condição fnserial > v_fnserial . Você deve gerar uma exceção quando a consulta principal retornar
null . IF NEW.timetype = 'Total' THEN
SELECT fnserial INTO v_fnserial
FROM mytable
WHERE timetype = 'Total' AND pcnum = NEW.pcnum AND fnname = NEW.fnname
ORDER BY fnserial DESC LIMIT 1;
SELECT SUM(timeelapse) FROM (
SELECT DISTINCT ON (floor(timeindex)::int) floor(timeindex)::int timeindex, timeelapse
FROM mytable
WHERE fnserial > coalesce(v_fnserial, 0) AND pcnum = NEW.pcnum AND fnname = NEW.fnname AND timetype = 'Lap'
ORDER BY 1, 2 DESC) alias
INTO v_sumtimeelapse_fn;
IF v_sumtimeelapse_fn NOTNULL THEN
NEW.timeelapse := v_sumtimeelapse_fn;
ELSE
RAISE EXCEPTION USING MESSAGE = 'There is not any previous row...';
END IF;
END IF;