简体   繁体   English

SQL 查询根据几个条件查找持续时间

[英]SQL query to find duration based on several criteria

I have a table named status with following data in it:我有一个名为status的表,其中包含以下数据:

time       var  value
12:00:01    a   10
12:00:01    b   10
12:00:01    c   12
12:00:05    a   9
12:00:05    b   10
12:00:05    c   10
12:00:10    a   13
12:00:10    b   1
12:00:10    c   4
14:00:01    a   12
14:00:01    b   11
14:00:01    c   9
14:00:41    a   9
14:00:41    b   9
14:00:41    c   3

Now I want to find the duration for which A > 10 and B > 10 I want the answer as: 44 sec (duration from 12:00:01 to 12:00:05 = 4 sec, duration from 14:00:01 to 14:00:41 = 40 sec, total 44 sec) I tried:现在我想找到A > 10B > 10我想要答案的持续时间:44 秒(持续时间从 12:00:01 到 12:00:05 = 4 秒,持续时间从 14:00:01 到14:00:41 = 40 秒,总共 44 秒)我试过:

SELECT sum(time) as duration FROM status WHERE A>10 AND B>10;

This is a gaps and islands problem, which can be solved using a cumulative sum.这是一个间隙和孤岛问题,可以使用累积和来解决。 The lag() is used to determine where islands start. lag()用于确定岛屿的开始位置。 The cumulative sum defines groups.累积总和定义组。

SQL date/time functions are notoriously database-dependent.众所周知,SQL 日期/时间函数依赖于数据库。 So the following gives the right idea, but it may not work directly in your database.所以下面给出了正确的想法,但它可能无法直接在您的数据库中工作。 So, the times when the condition occurs is returned by the following query:因此,条件发生的时间由以下查询返回:

select min(time), max(time)
from (select t.*,
             sum(case when a < 10 or b < 10 then 1 else 0 end) over (order by time) as grp
      from status t
     ) t
where a > 10 and b > 10;

The sum() is then an aggregation on this. sum()然后是对此的聚合。 For instance:例如:

select sum(maxtime - mintime)
from (select max(time) as maxtime, min(time) as mintime
      from (select t.*,
                   sum(case when a < 10 or b < 10 then 1 else 0 end) over (order by time) as grp
            from status t
           ) t
      where a > 10 and b > 10
     ) t

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

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