当系列更改时,查找列中连续系列的最小最大值

时间:2019-02-13 03:07:02

标签: sql sql-server

我有一个表,该表包含3列:时间,Tagid和具有数百万或行的Intvalue。 当Intvalue的行数据从hi变为low时,我想找到Intvalue列的最小值和最大值。

如何编写SQL查询以获取以下结果: enter image description here

2 个答案:

答案 0 :(得分:2)

嗯。假设可以使用lead()lag()

select t.*
from (select t.*,
             lag(intvalue) over (partition by tagid order by time) as prev_iv,
             lead(intvalue) over (partition by tagid order by time) as next_iv
      from t
     ) t
where prev_intvalue is null or
      next_intvalue is null or
      (intvalue > prev_intvalue and intvalu > next_intvalue)

答案 1 :(得分:0)

您可以尝试以下查询。

Select *
From (
        SELECT  DATEADD(HH,-5,DATEADD(s,t_stamp/1000,'1970-01-01 00:00:00')) as Time,[tagid]
              ,[intvalue]
              -- ROW_NUMBER() OVER (ORDER BY t_stamp) AS rn
               ,lag(intvalue) over (partition by tagid order by t_stamp) as prev_iv,
               lead(intvalue) over (partition by tagid order by t_stamp) as next_iv
          FROM [IgnHistorianDB].[dbo].[sqlt_data_5_2019_02]
          where tagid=353
    ) t   
Where 
       prev_iv is null or
       next_iv is null or
      (intvalue > prev_iv and intvalue> next_iv)