BY a.the_geom <-> the_geom LIMIT 1) as first, (SELECT cartodb_id FROM axh_roads ORDER BY a.the_geom <-> the_geom OFFSET 1 LIMIT 1) as second, (SELECT cartodb_id FROM axh_roads ORDER BY a.the_geom <-> the_geom OFFSET 2 LIMIT 1) as third FROM axh_openpaths a) UPDATE axh_roads b SET openpaths_score = openpaths_score + 0.5 * (SELECT count(*) FROM points WHERE first = b.cartodb_id) + 0.3 * (SELECT count(*) FROM points WHERE second = b.cartodb_id) + 0.2 * (SELECT count(*) FROM points WHERE third = b.cartodb_id) The Algorithm in SQL