获取初始序列的“最后”行

问题描述 投票:0回答:2

我有一张桌子,如下所示

示例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-server ssms
2个回答
0
投票

这里是使用窗口函数的替代方法:

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

0
投票

我们可以使用简单的left joinmin()max()函数来实现

© www.soinside.com 2019 - 2024. All rights reserved.