首页 > 解决方案 > 在 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

标签: sql-serverselect

解决方案


有了这张桌子

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

推荐阅读