Un método usa lag()
:
select t.*
from (select t.*,
lag(status) over (partition by val, name order by date) as prev_status
from t
) t
where status = 'open' and
(prev_status is null or prev_status <> 'open');
Esto puede devolver más de un resultado para una prueba, si el estado puede "regresar" a 'open'
. Puedes usar row_number()
si no desea este comportamiento:
select t.*
from (select t.*,
row_number() over (partition by val, name, status order by date) as seqnum
from t
) t
where status = 'open' and seqnum = 1;
EDITAR:
(para datos ajustados)
Simplemente puede usar la agregación condicional:
select val, name,
min(case when status = 'open' then status end) as o_gate,
min(case when status = 'open' then dt end) as o_dt,
max(case when status = 'close' then status end) as c_gate,
max(case when status = 'close' then dt end) as c_dt,
from t
group by val, name;
Aquí es un db<>violín
Si desea reconstruir el id
, puede usar una expresión como:
row_number() over (order by min(dt)) as id