PLSQL-满足条件时的测量持续时间

时间:2011-03-22 18:41:02

标签: sql oracle plsql

假设一个表格如下所示:

time    name availability
10:00   A   100
10:05   A   0
10:10   A   0
10:15   A   0
10:20   A   0
10:25   A   0
10:30   A   100
10:35   A   0
10:40   A   0
10:45   A   100
10:50   A   100
10:55   A   0
11:00   A   100
11:05    A   0

我想计算可用性等于零的每个事件的持续时间,这不仅意味着计数为“0”,而是在下一个值再次变为100之前,第一个零和最后一个零之间的持续时间是多少。

例如,在我的表中,我有3对事件(向上= 100,向下= 0,向上),其中第一个持续25分钟(10:05-10:25),第二个持续10分钟,第三个持续5分钟。最后一个零不是上下事件的一部分!

2 个答案:

答案 0 :(得分:1)

至少在我不知情的情况下,这不会得到原始美的回答。

但是,要做到这一点并不难。但是,您必须成为具有分析功能的朋友。在这种情况下:滞后和领导。

如果这是你想得到的(我很肯定你可以自己计算差异,有趣的部分是获得范围),然后查看下面的查询:

10:00   A   100     
10:05   A   0   10:05   10:25
10:10   A   0   10:05   10:25
10:15   A   0   10:05   10:25
10:20   A   0   10:05   10:25
10:25   A   0   10:05   10:25
10:30   A   100     
10:35   A   0   10:35   10:40
10:40   A   0   10:35   10:40
10:45   A   100     
10:50   A   100     
10:55   A   0   10:55   10:55
11:00   A   100     
11:05   A   0   11:05   11:05

with startTime as
(
  SELECT time
        ,Name
        ,case
           when t.availability = 0 and
           /* see the default value passed to "lag", 
              if nothing gets returned (first row), we return 2 which is > 0 */
                 lag(availability, 1,2) OVER(partition BY Name ORDER BY time) > 0 then 
            time
         end start_time
  FROM   SampleTable t
)
,stopTime as
(
  SELECT time
        ,name
        ,case
           when t.availability = 0 and
           /* see the default value passed to "lead" 
              if nothing gets returned (last row), we return 2 which is > 0*/
                (lead(availability, 1, 2) OVER(partition BY Name ORDER BY time) > 0) then
            time
         end stop_time
  FROM   SampleTable t
)
SELECT t.time
      ,t.Name
      ,t.availability
      ,case
         when t.availability = 0 then
          (SELECT Max(start_time)
           FROM   startTime
           WHERE  start_time is not null
           and    time <= t.time)
       end as start_time
      ,case
         when t.availability = 0 then
          (SELECT Min(stop_time)
           FROM   stopTime
           WHERE  stop_time is not null
           and    time >= t.time)
       end as stop_time
FROM   SampleTable t
ORDER  BY t.time

答案 1 :(得分:0)

LAG功能可以帮助您: Oracle LAG function

相关问题