假设有如下表格:
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事件的一部分!
发布于 2011-03-23 09:18:54
这不会用原始的美来回答,至少据我所知不会。
不过,要做到这一点并不难。不过,您必须与分析函数成为朋友。在本例中: Lag和Lead。
如果这就是你想要得到的(我敢肯定你可以自己计算差值,有趣的部分是得到范围),那么看看下面的查询:
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
发布于 2011-03-23 09:17:42
LAG函数可以帮助您:Oracle LAG function
https://stackoverflow.com/questions/5396209
复制