PostgreSQL DISTINCT ON

SELECT DISTINCT ON (time_bucket('5 minutes', created_at)) * FROM histories;

SELECT DISTINCT ON (time_bucket) time_bucket('5 minutes', created_at), * FROM histories ORDER BY time_bucket, created_at ASC;
History.select("DISTINCT ON (time_bucket('5 minutes', created_at)) *")