首页 > 解决方案 > 获取初始序列的“最后”行

问题描述

我有一张如下表

示例 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 中,它运行不正确。

标签: sql-serverssms

解决方案


这是使用窗口函数的另一种方法:

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')

推荐阅读