如何 select 具有零值的时间间隔

How to select time intervals with zero values

我需要 select 没有 (0) 数据的时间间隔。如何在 SQL?

中做到这一点

示例:

Time Data
10:00 0
10:15 0
10:30 1
10:45 0
11:00 12
11:15 0
11:30 0
11:45 0
12:00 7

结果:

10:00 - 10:30
10:45 - 11:00
11:15 - 12:00

您需要确定分组,然后根据分组进行聚合。

一个简单的方法是计算每个值上或之后的非零值的数量。这带来了结束时间:

select min(time), max(time)
from (select t.*,
             sum(case when data > 0 then 1 else 0 end) over (order by time desc) as grp
      from t
     ) t
group by grp
having min(data) = 0
order by min(time);

Here 是一个 SQL Fiddle.

注意:这使用 window/analytic 大多数数据库支持的标准 SQL 函数。

大多数 DBMS 支持 Windowed Aggregates:

with cte as 
 (
   select time, data,
      -- assign a new group number whenever it's not a zero
      -- = same number for a value and following zeroes
      sum(case when data = 0 then 0 else 1 end) 
          over (order by time desc -- start from the latest row
                rows unbounded preceding) as grp 
   from myTable
 ) 
select
   min(time), max(time)
from cte
group by 
   grp -- aggregate previous zeroes with the non-zero row