在MSSQL中选择带有条件的上一行和下一行

时间:2019-05-20 05:53:19

标签: sql-server select

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

查找值大于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

2 个答案:

答案 0 :(得分:1)

使用此表

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

答案 1 :(得分:0)

是否正在寻找类似的东西?

SELECT * 
FROM table 
WHERE id IN 
(
    SELECT DISTINCT id 
    FROM table 
    WHERE Val >249
) 
AND Val > 149