sql-server - 获取初始序列的“最后”行
问题描述
我有一张如下表
示例 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 中,它运行不正确。
解决方案
这是使用窗口函数的另一种方法:
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')
推荐阅读
- python - 如何在views.py中调用django自定义编写的AuthenticationBackend的authenticate()方法?
- matlab - 如何在同一轴上绘制三个同时图?
- android - 您不能在 onCreate 调用错误之前请求 ViewModel
- android - 无法从 Android 调用 React 本机函数
- java - 如何将隐私政策添加到 Android 应用程序?
- python-3.x - WindowManager 的 NameError 实例未定义 kivy
- javascript - 由机器人创建的 Javscript / Ajax 帐户
- c++ - 用 unique_ptr 实现的二叉搜索树中的迭代 findMin()
- php - 不允许 axios 发布 405 | Laravel + vue.js
- php - 如何解决 phpMyAdmin xampp 中的“无权限”错误