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

时间:2019-10-25 02:37:33

标签: sql-server ssms

我有一张桌子,如下表

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

2 个答案:

答案 0 :(得分: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')

答案 1 :(得分:0)

我们可以使用简单的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';