您可以通过使用 CTE 来实现这一点(通用表表达式 https://web.archive.org/web/20210927200924/http://www.4guysfromrolla.com/webtech/071906-1.shtml).
下面的查询适用于 SQL Server 的 Adventure Works 演示表(“速度限制”为 7)。
这是受到 SO 上另一个问题的强烈启发:SQL 中连续行的 GROUP BY https://stackoverflow.com/questions/1136597/group-by-for-continuous-rows-in-sql.
with CTE as (
select
ROW_NUMBER() over(order by SalesTaxRateID) as RowNo
, *
from
Sales.SalesTaxRate
)
, MyLogGroup as (
select
l.*
,(select
max(SalesTaxRateID)
from
CTE c
where
not exists (select * from CTE
where RowNo = c.RowNo-1
and TaxRate > 7
and c.TaxRate > 7)
and c.SalesTaxRateID <= l.SalesTaxRateID) as GroupID
from
Sales.SalesTaxRate l)
select
min(SalesTaxRateID) as minimum
, max(SalesTaxRateID) as maximum
, avg(TaxRate)
from
MyLogGroup
group by
GroupID
having
min(TaxRate) > 7
order by
minimum
这些内容应该适合您:
with CTE as (
select
ROW_NUMBER() over(order by [Time]) as RowNo
, *
from
<table_name>
)
, MySpeedGroup as (
select
s.*
,(select
max([Time])
from
CTE c
where
not exists (select * from CTE
where RowNo = c.RowNo-1
and Velocity > <speed_limit>
and c.Velocity > <speed_limit>)
and c.[Time] <= s.[Time]) as GroupID
from
<table_name> l)
select
min([Time]) as minimum
, max([Time]) as maximum
, avg([Velocity]) -- don't know if you want this
from
MySpeedGroup
group by
GroupID
having
min(Velocity) > <speed_limit>
order by
minimum