繁体   English   中英

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

[英]how to select a consecutive rows that satisfy a condition in sql

我有一个包含2列的表,第一列是RecordTime,第二列是相应的度量。 我想选择前三个小时间隔,每个间隔> 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

您没有指定什么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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM