sql >> Database teknologi >  >> RDS >> PostgreSQL

Forespørger efter en 'run' af på hinanden følgende kolonner i Postgres

Her er den RECURSIVE CTE-løsning. (øer-og-gaps-problemer egner sig naturligvis til rekursiv CTE)

WITH RECURSIVE runrun AS (
    SELECT event_id, event_time
    , event_time - ('30 sec'::interval) AS low_time
    , event_time + ('30 sec'::interval) AS high_time
    FROM table1
    UNION
    SELECT t1.event_id, t1.event_time
    , LEAST ( rr.low_time, t1.event_time - ('30 sec'::interval) ) AS low_time
    , GREATEST ( rr.high_time, t1.event_time + ('30 sec'::interval) ) AS high_time
    FROM table1 t1
    JOIN runrun rr ON t1.event_time >= rr.low_time
                  AND t1.event_time < rr.high_time
    )
SELECT DISTINCT ON (event_id) *
FROM runrun rr
WHERE rr.event_time >= '2011-01-01 00:00:15'
AND rr.low_time <= '2011-01-01 00:00:15'
AND rr.high_time > '2011-01-01 00:00:15'
    ;
 

Resultat:

event_id | event_time | low_time | high_time ----------+---------------------+---------------------+--------------------- 2 | 2011-01-01 00:00:15 | 2010-12-31 23:59:45 | 2011-01-01 00:00:45 3 | 2011-01-01 00:00:29 | 2010-12-31 23:59:45 | 2011-01-01 00:01:28 4 | 2011-01-01 00:00:58 | 2010-12-31 23:59:30 | 2011-01-01 00:01:28 (3 rows)

  1. Import af CSV-data til Rails-appen ved at bruge noget andet end foreningens id

  2. Diff. mellem datoer - SQL plus

  3. Problemer med at vise blob-billeder

  4. Postgres IKKE I ydelse