CREATE TABLE tests(timestamp bigint, val int); INSERT INTO tests(timestamp, val) VALUES (1514768400, 2), (1514768401,4), (1514769299,6), (1514769300,8), (1514769301,10), (1514770199,12), (1514770200,14), (1514770201,16), (1514771099,18), (1514771100,18), (1514771101,20), (1514771999,22); select distinct on (qwe) qwe,val1 from ( select (date_trunc('seconds', (to_timestamp(timestamp) - timestamptz 'epoch') / extract(epoch from interval '600 sec')) * extract(epoch from interval '600 sec') + timestamptz 'epoch') as qwe , val as val1 from tests order by qwe asc ) as tests2 order by qwe ; ------------------ select avg(b.val) diff ...