SELECT DISTINCT ON (maxspeed, x.assetid) x.assetid, x(transform(x.position, 99999)) AS xpoint, y(transform(x.position, 99999)) AS ypoint, ts, maxspeed, fleet, tagid, heading, poweron FROM ( SELECT ap.*, maxspeed, apidx FROM( SELECT assetid , max((speed::NUMERIC * (10^22)::NUMERIC) + asset_positions.id)::NUMERIC as apidx , max(speed) as maxspeed FROM asset_positions WHERE Distance(asset_positions.position, transform( GeomFromEWKT('SRID=99999;POLYGON((-9231299.906000735 4839195.409207389 0,-9231414.561543163 4828879.028734494 0,-9250256.28901546 4828079.607960547 0,-9250753.129699312 4840489.72123508 0,-9231299.906000735 4839195.409207389 0))'), 4326 )) = 0 AND ts between '2007-10-05T00:00:00-07:00'::TIMESTAMP AND '2007-10-05T23:59:00-07:00'::TIMESTAMP AND assetid IS NOT NULL AND speed::NUMERIC > 15277.777778 GROUP BY assetid ) AS innertable INNER JOIN asset_positions ap ON ap.id = (apidx - (maxspeed::numeric*(10^22)::NUMERIC))::BIGINT WHERE ap.id = (apidx - (maxspeed::numeric*(10^22)::NUMERIC))::BIGINT ) x INNER JOIN asset ON asset.id =x.assetid WHERE asset.id=x.assetid