2015-10-13 38 views
0

我期待列出開始時間結束時間當門被OPEN這個樣本數據如何獲得的開始時間和結束時間爲每個狀態

下面是一些示例數據表

currenttime,  door_status, 
12-10-15 12:02:00 Open 
12-10-15 12:01:00 Open 
12-10-15 12:00:30 Open 
12-10-15 11:59:30 Open 
12-10-15 11:59:00 Open 
12-10-15 11:58:30 Open 
12-10-15 11:58:00 Closed 
12-10-15 11:57:30 Closed 
12-10-15 11:57:00 Open 
12-10-15 11:56:00 Open 
12-10-15 11:55:30 Open 
12-10-15 11:55:00 Open 

這裏是預期的結果

start_Time    end_Time    time_it_was_open 

12-10-15 11:58:30  12-10-15 12:02:00  3 mins 30 secs 
12-10-15 11:55:00  12-10-15 11:57:00  2 mins 

試圖查詢

查詢1:

SELECT current_time_open, current_time_closed, door1 FROM(
SELECT 
    CASE 
     WHEN door1 = 'Open' THEN currenttime 
    END AS current_time_open, 
    CASE 
     WHEN door1 = 'Closed' THEN currenttime 
    END AS current_time_closed, 
    door1 
FROM 
    (SELECT 
     r1.currenttime, r1.temp, r1.door1 
    FROM 
     rcs_data r1) as g1 GROUP BY currenttime DESC) as t1; 

查詢2:

SELECT MAX(current_time_open), MAX(current_time_closed), TIMEDIFF(MAX(current_time_open),MAX(current_time_closed)) FROM (SELECT 
    CASE 
     WHEN door1 = 'Open' THEN currenttime 
    END AS current_time_open, 
    CASE 
     WHEN door1 = 'Closed' THEN currenttime 
    END AS current_time_closed 
FROM 
    (SELECT 
     currenttime, temp, door1 
    FROM 
     rcs_data) as g1 GROUP BY currenttime DESC) as t1; 
+0

到目前爲止您嘗試過了什麼?編輯您的問題並添加您的嘗試查詢。 – BrokenBinary

+0

請添加一個「預期結果」區塊,因爲它可以幫助我們使用您的虛擬數據來達到您的期望。 –

+0

我已經添加了。 @MarcoAurélioDeleu –

回答

0

這裏一個變種做到這一點:

select *, unix_timestamp(endtime)-unix_timestamp(starttime) as dur_seconds 
from (
select min(currenttime) as starttime, max(currenttime) as endtime 
from (
select currenttime, coalesce(
(select min(currenttime) from t as b where b.currenttime > a.currenttime and b.door_status != a.door_status), 
(select max(currenttime) from t as b where b.currenttime > a.currenttime and b.door_status = a.door_status), 
a.currenttime) as mxt 
from t as a 
where a.door_status = 'Open' 
) as q 
group by mxt 
) as q2 

因此,主要想法是爲「打開」狀態組「分配」一些唯一ID,在這種特定情況下,其第一次關閉狀態或最後一次打開狀態,或當前時間爲最後一次「打開」 「表格中的狀態

+0

美麗,非常感謝@Lashane,它的工作原理 –

相關問題