Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Oracle Counting Clusters

Tags:

sql

oracle

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

  1. Number of shutdowns: The Number of shut down in this case is 3 based on 0 is ON and 1 is OFF.
  2. Period Between every shut down

    Example:

    1. From: 07-Jul-15 12:05:00 To: 07-Jul-15 12:15:00 Duration : 15 Mins
    2. From: 07-Jul-15 12:35:00 To: 07-Jul-15 12:50:00 Duration : 20 Mins

I am using Oracle

like image 739
szakwani Avatar asked Oct 31 '22 00:10

szakwani


1 Answers

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

like image 118
valex Avatar answered Nov 15 '22 05:11

valex