1つのメソッドは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');
ステータスが'open'
に「戻る」ことができる場合、これはテストに対して複数の結果を返す可能性があります 。 row_number()
を使用できます この動作を望まない場合:
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;
編集:
(調整済みデータの場合)
条件付き集計を使用できます:
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;
こちら db<>フィドル
です
id
を再構築する場合 、次のような式を使用できます:
row_number() over (order by min(dt)) as id