我有一个Postgres表,其中包含以下数据
#Id Time Setting
10x, 9/11/2018 12:01, 1
10x, 9/11/2018 12:04, 0
11x, 9/7/2018 14:47, 1
11x, 9/7/2018 14:48, 0
11x, 9/7/2018 14:49, 1
11x, 9/7/2018 14:50, 0
数据已经按照ID,时间按升序排序。 我的目标是计算给定id的“设置”从1更改为0的连续行之间的时间差。我可以放心地假设行数是偶数,并且每行设置为“ Setting”(1)的行都紧随其后的是设置为“ 0”的行
预期输出
# Id, Duration
10x, 3min
11x, 1min
11x, 1min
答案 0 :(得分:0)
在以下情况下,您可以尝试使用$insert_on_duplicate_update_query = str_replace(array("'NULL'","'null'"), 'null', $insert_on_duplicate_update_query);
函数:
lag()
其中select t2.Id,
cast((60*cast(to_char(t2.l_time,'hh24') as int)+
cast(to_char(t2.l_time,'mi') as int)) as varchar)||' min'
as Duration
from
(
select t1.*,
lag(setting) over (order by id,time) l_setting,
time - lag(time) over (order by id,time) l_time
from tab t1
) t2
where t2.setting = 0 and l_setting = 1;
id duration
--- --------
10x 3 min
11x 1 min
11x 1 min
被假定为时间戳类型列。