如何在SQL Server中特定值之后选择下一个值?

时间:2018-12-15 09:44:34

标签: sql sql-server partition row-number

enter image description here enter image description here

我想选择stat = idle之后的值

3 个答案:

答案 0 :(得分:2)

with cte as 
 (
    select *,
       case when lag(stat,1,'idle') over (order by time) = 'idle' -- previous row is idle
             and stat <> 'idle'                                   -- current row is not idle
            then 1
            else 0
       end as flag 
    from tab
 )
select * from cte
where flag = 1

这也返回第一行,如果要排除它,请从lag中删除默认值。

答案 1 :(得分:0)

您可以使用滞后尝试以下查询,如下所示

create table #temp (id int identity (1,1), times datetime, gps_speed decimal(18,2),I2 int, stat varchar(20), row_num int)
insert into #temp values 
('2018-12-14', 18.52, 1, 'running', 4),
('2018-12-14', 0, 1, 'idle', 5),
('2018-12-14', 24.08, 1, 'running', 6),
('2018-12-14', 37.04, 1, 'running', 29),
('2018-12-14', 0, 1, 'idle', 30),
('2018-12-14', 0, 1, 'idle', 32),
('2018-12-14', 18.52, 1, 'running', 37),
('2018-12-14', 35.19, 1, 'running', 41),
('2018-12-14', 16.67, 1, 'running', 42),
('2018-12-14', 0, 1, 'idle', 43),
('2018-12-14', 0, 1, 'idle', 44)    

select * from (
select 
      lag(stat, 1) OVER(ORDER BY [id]) as Prev,*
from #temp
)a where Prev <> stat
and Prev = 'idle' or Prev is null

输出如下所示

Prev    id  times   gps_speed           I2  stat     row_num
NULL    1   14.12.2018 00:00:00 18,52   1   running  4
idle    3   14.12.2018 00:00:00 24,08   1   running  6
idle    7   14.12.2018 00:00:00 18,52   1   running  37

这是现场演示-Demo <> Prev Value

答案 2 :(得分:-1)

        SELECT * FROM TABLE WHERE   
        ROWNUM>ANY(SELECT  
         Max(ROWNUM)
         FROM TABLE WHERE 
        STATUS='IDLE')

这应该可以正常工作,我想获得所需的含义,即外部查询正在逐行工作,子查询仅在其状态为空闲时返回rownum