Salah satu metode menggunakan 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');
Ini dapat mengembalikan lebih dari satu hasil untuk pengujian, jika statusnya dapat "kembali" ke 'open'
. Anda dapat menggunakan row_number()
jika Anda tidak menginginkan perilaku ini:
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;
EDIT:
(untuk data yang disesuaikan)
Anda cukup menggunakan agregasi bersyarat:
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;
Di sini adalah db<>biola
Jika Anda ingin merekonstruksi id
, Anda dapat menggunakan ekspresi seperti:
row_number() over (order by min(dt)) as id