Puede usar variables muy bien en PL/pgSQL.
Resolvería esto con una función de tabla.
Asumiendo que la tabla se llama stock
, mi código se vería así:
CREATE OR REPLACE FUNCTION combine_periods() RETURNS SETOF stock
LANGUAGE plpgsql STABLE AS
$$DECLARE
s stock;
period stock;
BEGIN
FOR s IN
SELECT stock_name, action, start_date, end_date
FROM stock
ORDER BY stock_name, action, start_date
LOOP
/* is this a new period? */
IF period IS NOT NULL AND
(period.stock_name <> s.stock_name
OR period.action <> s.action
OR period.end_date <> s.start_date)
THEN
/* new period, output last period */
RETURN NEXT period;
period := NULL;
ELSE
IF period IS NOT NULL
THEN
/* period continues, update end_date */
period.end_date := s.end_date;
END IF;
END IF;
/* remember the beginning of a new period */
IF period IS NULL
THEN
period := s;
END IF;
END LOOP;
/* output the last period */
IF period IS NOT NULL
THEN
RETURN NEXT period;
END IF;
RETURN;
END;$$;
Y lo llamaría así:
test=> SELECT * FROM combine_periods();
┌────────────┬─────────┬────────────┬──────────┐
│ stock_name │ action │ start_date │ end_date │
├────────────┼─────────┼────────────┼──────────┤
│ google │ falling │ 3 │ 4 │
│ google │ growing │ 1 │ 3 │
│ google │ growing │ 4 │ 5 │
│ yahoo │ growing │ 1 │ 2 │
└────────────┴─────────┴────────────┴──────────┘
(4 rows)