我有一张如下所示的表格:
会话ID | 行动 | 位置 |
---|---|---|
会话_1 | 1 | 0 |
会话_1 | 0 | 1 |
会话_1 | 1 | 2 |
会话_1 | 0 | 3 |
会话_2 | 0 | 0 |
会话_2 | 1 | 1 |
会话_2 | 0 | 2 |
会话_2 | 0 | 3 |
我想在最后一个操作后删除行。
预期结果应该是:
会话ID | 行动 | 位置 |
---|---|---|
会话_1 | 1 | 0 |
会话_1 | 0 | 1 |
会话_1 | 1 | 2 |
会话_2 | 0 | 0 |
会话_2 | 1 | 1 |
一种方法是使用 CTE 来获取 max(position),其中每个会话 id 的操作为 1。然后加入它并返回位置小于或等于 cte 的 max 的位置。
with cte as (
select session_id, max(position) as max_pos
from table1
where action = 1
group by session_id
)
select t.*
from table1 t
join cte c
on t.session_id = c.session_id
where t.position <= c.max_pos