sql-server - 在 MSSQL 中选择带有条件的上一行和下一行
问题描述
ID BegCha EnCha Val
10 20 30 250
10 30 40 140
10 50 60 189
20 10 20 250
20 20 30 157
20 30 40 199
20 40 50 70
查找 value 大于 249 的所有行
select * from table where Val >249
select One row previous and one row after if the values are 50 of 250
select * from table where id in (select * from table where Val >249) and Val > 149
我期望得到如下:
ID BegCha EnCha Val
10 20 30 250
10 30 40 140
10 50 60 189
20 10 20 250
20 20 30 157
解决方案
有了这张桌子
create table prueba(
id int ,
BegCha int,
EndCha int,
Val int);
这个数据
id BegCha EndCha Val
10 20 30 250
10 30 40 140
10 50 60 189
20 10 20 250
20 20 30 157
20 30 40 199
20 40 50 70
和这个查询
WITH pruebaNumerada AS
(
SELECT
ROW_NUMBER() OVER(ORDER BY id ASC) AS RowNumber,
id, BegCha, EndCha, val
FROM prueba
)
SELECT b.id, b.BegCha, b.EndCha, b.val
FROM pruebaNumerada a
inner join pruebaNumerada b on b.RowNumber between a.RowNumber-1 and a.RowNumber+1
WHERE a.val >=250;
我得到这个结果
id BegCha EndCha val
10 20 30 250
10 30 40 140
10 50 60 189
20 10 20 250
20 20 30 157
推荐阅读
- vue.js - 如何修改子Vue组件中的值
- angular - 嵌套数组上的AngularTS递归过滤器
- c - 对于几乎相同的代码,C 的行为不同
- python - 如何从 python panda 数据框中删除不需要的数据?
- asp.net - 从加入的注册模型中选择事件数据时检索所有与会者数据
- tensorflow - 防止混合来自不同 TFRecords 文件的训练示例
- swift - 实例化子类在 Swift Playground 中有效,但使用类本身却不行
- angular - 命令行界面安装中间的问题
- javascript - 如何让网络用户能够使用代码控制我的代码?
- python - django 在查询集上添加来自反向一对多关系的列