SQL: selecting rows with only values ​​separated by a given interval from other results

Let's say that I have a table that looks like this, giving me the time of various events in seconds.

event_time
----------
11
14
18
20
25
39
42
43
50

I am trying to find a query that will give me a set of rows from this table, where each row will be split for at least 10 seconds from the other rows as a result.

Desired Result:

event_time
----------
11
25
39
50

Line c is event_time=11included because there is nothing in front of it. Line c event_time=25is the next one to be returned, because it is the first line that is at least 10 seconds from line c event_time=11.

Postgres. /CTE, ORDER BY, LIMIT .., Postgres, -, .

+4
3

/CTE, ORDER BY, LIMIT .., Postgres, -, .

with recursive 
  t(x) as ( --Test data
    select * from unnest('{11,14,18,20,25,39,42,43,50,55,60,61,69,70,71}'::int[])
    order by random()),
  r(x) as (
    select min(x) as x from t
    union all
    (select t.x from t join r on (t.x >= r.x + 10) order by t.x limit 1))
select * from r;

http://rextester.com/VHOGH66762

.

+2

plpgsql, ( ).

create or replace function strain_events()
returns setof events language plpgsql as $$
declare
    curr record;
    prev int;
begin
    for curr in
        select *
        from events
        order by 1
    loop
        if prev is null or curr.event_time >= prev + 10 then
            return next curr;
            prev = curr.event_time;
        end if;
    end loop;
end $$;

select * from strain_events();
+2

I think this request will work

select distinct  event_time_b
from
(
select event_time_a , min(event_time_b) event_time_b
from
(
select a.event_time event_time_a , b.event_time event_time_b , b.event_time-a.event_time diff
 from (select 0 as event_time union select event_time from  so_ques) a , so_ques b
where a.event_time<>b.event_time
and  b.event_time-a.event_time>=10
order by a.event_time
) a
group by event_time_a
order by event_time_a
) a
order by 1
;

Table name = so_ques (created for testing)

0
source

Source: https://habr.com/ru/post/1669431/


All Articles