首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >PLSQL-在满足条件时测量持续时间

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

Stack Overflow用户
提问于 2011-03-23 02:41:02
回答 2查看 155关注 0票数 1

假设有如下表格:

代码语言:javascript
代码运行次数:0
运行
复制
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对事件(up=100、down=0、up),第一对事件持续25分钟(10:05-10:25),第二对事件持续10分钟,第三对事件持续5分钟。最后一个零不是up-down-up事件的一部分!

EN

回答 2

Stack Overflow用户

发布于 2011-03-23 17:18:54

这不会用原始的美来回答,至少据我所知不会。

不过,要做到这一点并不难。不过,您必须与分析函数成为朋友。在本例中: Lag和Lead。

如果这就是你想要得到的(我敢肯定你可以自己计算差值,有趣的部分是得到范围),那么看看下面的查询:

代码语言:javascript
代码运行次数:0
运行
复制
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

代码语言:javascript
代码运行次数:0
运行
复制
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
EN

Stack Overflow用户

发布于 2011-03-23 17:17:42

LAG函数可以帮助您:Oracle LAG function

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5396209

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档