获取初始序列的 "last" 行

Get "last" row of the initial sequence

我有一个table如下

示例 1:

ID      Code
1       A002
2       A001
3       A001
4       A002
5       A001
6       A002

我想获取 A001 的最后一行(初始序列)。结果应该是 ID = 3

示例 2:

ID      Code
1       A001
2       A001
3       A001
4       A002
5       A001
6       A002

我想获取 A001 的最后一行(初始序列)。结果应该是 ID = 3

示例 3

ID      Code
1       A001
2       A002
3       A001
4       A002
5       A001
6       A002

我想获取 A001 的最后一行(初始序列)。结果应该是 ID = 1

我该怎么做?

我尝试运行下面的代码

select t.*
from t
where t.id < (select min(t2.id)
              from t t2
              where t2.code <> 'A001'  -- not NOT EQUALS
             ) 
order by t1.id desc;

但在示例 1 中,它 运行 不正确。

这是使用 window 函数的替代方法:

select max(id)
from (select min(case when code <> 'A001' and id < min_a001_id
                      then id end
                 end) as min_next_id
      from (select t.*
                   min(case when code = 'A001' then id end) over () as min_a001_id
            from t
           ) t
     ) t
where code = 'A001' and
      (min_next_id is null or id < min_next_id);

另一种方法使用 lead() -- 第一次下一个 id 不是 A001:

select min(id)
from (select t.*,
             lead(code) over (order by id) as next_code
      from t
     ) t
where code = 'A001' and
      (next_code is null or next_code <> 'A001')

我们可以使用简单的 left join 加上 min()max() 函数来实现这一点

select coalesce(max(t2.id), min(t1.id)) from t as t1
left join t t2 on t2.id = t1.id + 1 and t2.code = t1.code
where t1.code = 'A001';