我希望使用此示例数据 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 :(得分: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对于" open"状态,在这种特殊情况下,它是关闭状态的第一次或打开状态的最后一次,或者是最后一次打开状态的当前时间。表中的状态