如何在sql中选择满足条件的连续行
我有一个有两列的表,第一列是RecordTime,第二列是相应的度量值。 我想选择前3个小时间隔,每个测量值>150,然后计算所选间隔的总和、平均值、最小值和最大值。 我该怎么做如何在sql中选择满足条件的连续行,sql,Sql,我有一个有两列的表,第一列是RecordTime,第二列是相应的度量值。 我想选择前3个小时间隔,每个测量值>150,然后计算所选间隔的总和、平均值、最小值和最大值。 我该怎么做 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:
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)
您使用的是什么数据库管理系统?SQL Server、MySQL、Oracle等等…?对不起,我正在使用SQL Server。查询中的[start]应该是什么?Thanks@user1433645-如果您想避免将CTE与as一起使用。。。可以将整个表达式复制到区间部分