This is my current oracle statement:
WITH table_ AS (
SELECT DATETIME
, TOTALTIME1
, RAWOUTPUT1
, CASE BITAND(RAWOUTPUT1, POWER(2,0))
WHEN 0 THEN 'FALSE'
ELSE 'TRUE'
END AS Pumpe1_1
FROM pump_box_hist
)
, table2_ AS (
SELECT DATETIME
, TOTALTIME1
, RAWOUTPUT1
, Pumpe1_1
, LEAD (Pumpe1_1) OVER (ORDER BY datetime) as next_
, LAG (Pumpe1_1) OVER (ORDER BY datetime) as priv_
FROM table_
)
SELECT DATETIME
, TOTALTIME1
, RAWOUTPUT1
, Pumpe1_1
FROM table2_
WHERE (
Pumpe1_1 = next_
AND Pumpe1_1 <> priv_
AND DATETIME > to_date('30.10.2014 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
AND DATETIME < to_date('02.11.2014 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
)
;
It works fine but it takes nearly 50 seconds to execute. Because the data is sorted by DATETIME the idea is to do a while loop to exit if DATETIME is bigger than the given. Inside this loop I would then use IF for the date smaller than the given. I tried a while but don't get it working.
The code I've tried:
WHILE (SELECT DATETIME FROM pump_box_hist) < to_date('02.11.2014 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
LOOP
IF DATETIME > to_date('30.10.2014 00:00:00', 'DD-MM-YYYY HH24:MI:SS') THEN
WITH table_ AS (
SELECT DATETIME
, TOTALTIME1
, RAWOUTPUT1
, CASE BITAND(RAWOUTPUT1, POWER(2,0))
WHEN 0 THEN 'FALSE'
ELSE 'TRUE'
END AS Pumpe1_1
FROM pump_box_hist
)
, table2_ AS (
SELECT DATETIME
, TOTALTIME1
, RAWOUTPUT1
, Pumpe1_1
, LEAD (Pumpe1_1) OVER (ORDER BY datetime) as next_
, LAG (Pumpe1_1) OVER (ORDER BY datetime) as priv_
FROM table_
)
SELECT DATETIME
, TOTALTIME1
, RAWOUTPUT1
, Pumpe1_1
FROM table2_
WHERE (
Pumpe1_1 = next_
AND Pumpe1_1 <> priv_
)
;
END IF;
END LOOP;
Error: unknown command in line 32 and 33 (Editor's note: these have been lines 11 and 12 in the original formatting containing
END IF;andEND LOOP;)
So how can I get the LOOP and IF working? Thanks
while,loopandifconstructs in plain SQL. Why aren't you just filtering the dates inside yourtable_CTE? Because the first and last values in the range would then not lag/lead values to set theirpriv_andnext_?