I have the following "starting" query:
select fecha as date,velocidad as speed, velocidad>100 as overspeed from reports.avl_historico_354898046636089 where fecha between '2017-04-19 00:00:00-03' and '2017-04-20 00:00:00-03' and velocidad>2 and ignicion=1 order by fecha; Which yields the following output:
date speed overspeed 2017-04-19 11:35:41+00,16,f 2017-04-19 11:37:01+00,24,f 2017-04-19 11:37:41+00,72,f 2017-04-19 11:38:21+00,82,f 2017-04-19 11:39:01+00,13,f 2017-04-19 11:39:41+00,68,f 2017-04-19 11:40:21+00,23,f 2017-04-19 11:41:01+00,57,f 2017-04-19 11:41:41+00,97,f 2017-04-19 11:42:21+00,96,f 2017-04-19 11:43:01+00,102,t 2017-04-19 11:43:41+00,104,t 2017-04-19 11:44:21+00,106,t 2017-04-19 11:45:01+00,109,t 2017-04-19 11:45:41+00,109,t 2017-04-19 11:46:21+00,114,t 2017-04-19 11:47:01+00,56,f 2017-04-19 11:47:28+00,54,f 2017-04-19 11:47:41+00,54,f 2017-04-19 11:48:21+00,54,f 2017-04-19 11:49:01+00,102,t 2017-04-19 11:49:07+00,104,t 2017-04-19 11:54:21+00,114,t 2017-04-19 11:55:01+00,118,t 2017-04-19 11:55:41+00,115,t 2017-04-19 11:56:21+00,111,t 2017-04-19 11:57:01+00,85,f 2017-04-19 11:57:41+00,45,f 2017-04-19 11:58:21+00,29,f 2017-04-19 12:00:35+00,4,f 2017-04-19 12:00:36+00,4,f ... And I've been trying to work with LAG/LEAD to get the first/last date for each group of rows where the overspeed column is TRUE, but I haven't been able to achieve the desired results, which could be like this:
start stop 2017-04-19 11:43:01+00 2017-04-19 11:46:21+00 2017-04-19 11:49:01+00 2017-04-19 11:56:21+00 Any ideas on how to get such output would be appreciated.
Original table DDL:
CREATE TABLE avl_historico_354898046636089 ( fecha timestamp with time zone NOT NULL, latitud double precision DEFAULT 0 NOT NULL, longitud double precision DEFAULT 0 NOT NULL, altitud double precision DEFAULT 0 NOT NULL, velocidad double precision DEFAULT 0 NOT NULL, cog double precision DEFAULT 0 NOT NULL, nsat integer DEFAULT 0 NOT NULL, tipo character(1), utc_hora time without time zone, fix_fecha date, imei bigint NOT NULL, registro timestamp with time zone, input1 integer DEFAULT 0, input2 integer DEFAULT 0, input3 integer DEFAULT 0, input4 integer DEFAULT 0, hdop double precision, adc double precision DEFAULT (-99), ignicion integer DEFAULT 1, adc2 double precision, power integer, driverid integer, ibutton2 integer, ibutton3 integer, ibutton4 integer, trailerid integer, adc3 double precision, adc4 double precision, horometro bigint, odometro bigint, panico integer DEFAULT 0, bateria double precision, bateriaint double precision );
copy (select fecha as date,velocidad as speed, velocidad>100 as overspeed from reports.avl_historico_354898046636089 where fecha between '2017-04-19 00:00:00-03' and '2017-04-20 00:00:00-03' and velocidad>2 and ignicion=1 order by fecha) to stdin delimiter ',';min, max(date) over (partition by overspeed)and thenlag leadto combine em