I have a data set which is based on a timestamp.
Date Value
07-Jul-15 12:05:00 1
07-Jul-15 12:10:00 1
07-Jul-15 12:15:00 1
07-Jul-15 12:20:00 0
07-Jul-15 12:25:00 0
07-Jul-15 12:30:00 0
07-Jul-15 12:35:00 1
07-Jul-15 12:40:00 1
07-Jul-15 12:45:00 1
07-Jul-15 12:50:00 1
07-Jul-15 12:55:00 0
07-Jul-15 13:00:00 0
07-Jul-15 13:05:00 1
07-Jul-15 13:10:00 1
07-Jul-15 13:15:00 1
07-Jul-15 13:20:00 0
07-Jul-15 13:25:00 0
I would like to query and return
- Number of shutdowns: The Number of shut down in this case is 3 based on 0 is ON and 1 is OFF.
Period Between every shut down
Example:
- From: 07-Jul-15 12:05:00 To: 07-Jul-15 12:15:00 Duration : 15 Mins
- From: 07-Jul-15 12:35:00 To: 07-Jul-15 12:50:00 Duration : 20 Mins
I am using Oracle
Using LEAD and LAG functions in ORACLE you can built these queries:
1.Number of shutdowns:
WITH IntTable AS
( SELECT * FROM
(
SELECT dt b_date,value,LEAD(dt) OVER (ORDER BY dt) e_date FROM
(
select "Date" dt,"Value" value,
LAG("Value") OVER (ORDER BY "Date") pvalue,
LEAD("Value") OVER (ORDER BY "Date") nvalue
from T
) T1
WHERE pvalue is NULL or value<>pvalue or nvalue is NULL
)
WHERE E_DATE is NOT NULL
)
SELECT COUNT(*) FROM IntTable where value = 0
SQLFiddle demo
2.Period Between every shut down
WITH IntTable AS
( SELECT * FROM
(
SELECT dt b_date,value,LEAD(dt) OVER (ORDER BY dt) e_date FROM
(
select "Date" dt,"Value" value,
LAG("Value") OVER (ORDER BY "Date") pvalue,
LEAD("Value") OVER (ORDER BY "Date") nvalue
from T
) T1
WHERE pvalue is NULL or value<>pvalue or nvalue is NULL
)
WHERE E_DATE is NOT NULL
)
SELECT b_date,e_date, (e_date-b_date) * 60 * 24 FROM IntTable where value = 1
SQLFiddle demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With