如何选择满足sql条件的连续行

时间:2015-11-16 16:19:02

标签: sql

我有一个包含2列的表,第一列是RecordTime,第二列是相应的度量。 我想选择每个度量的前3小时间隔> 150,然后计算所选间隔的SUM,AVG,MIN和MAX。 我怎样才能做到这一点 ?

RecordTime           Measure
----------------------------
11/11/2015 11:46:00 253.3333
11/11/2015 11:47:00 241.792
11/11/2015 11:48:00 300.768
11/11/2015 11:49:00 277.1893
11/11/2015 11:50:00 301.2267
11/11/2015 11:51:00 332.208
11/11/2015 11:52:00 271.52
11/11/2015 11:53:00 280.9067
11/11/2015 11:54:00 275.7227
11/11/2015 11:55:00 214.992
11/11/2015 11:56:00 235.4507
11/11/2015 11:57:00 279.3013
11/11/2015 11:58:00 407.136
11/11/2015 11:59:00 553.1573
11/11/2015 12:00:00 519.0667
11/11/2015 12:01:00 431.8507
11/11/2015 12:02:00 501.0027

1 个答案:

答案 0 :(得分:0)

您没有指定DBMS,但大多数DBMS都有公用表表达式(CTE)和日期函数。

CTE找到满足您标准的第一个间隔(前3小时,所有测量> 150)。最终选择为您提供统计信息

  with interval as (    
      select
         Min(recordTime) [Start],
      from [YourTable] T1
      where not exists
      (
         select 1
         from [YourTable] T2
         where 
           T2.RecordTime >= T1.RecordTime and
           T2.RecordTime < dateadd(hh, 3, T1.RecordTime) and
           T2.Measure > 150
      )    
   )
   select  
       Min(recordTime) as IntervalStart,
       SUM(Measure), AVG(Measure), MIN(Measure), MAX(Measure)
   from [YourTable]
   where 
     RecordTime >= (select [Start] from interval) and
     RecordTime < (select dateadd(hh, 3, [Start]) from interval)