Describe it.
$sql = 'with vals (beacon_id,power) as (values ';
foreach ($values as $k=>$v) {
$sql .= "('".pg_escape_string($k)."',".pg_escape_string($v)."),";
}
$sql = substr($sql, 0, -1).'), stats as (select location_name, beacon_id, avg(power) as power from beacons group by 1,2) select stats.location_name, sum(abs(stats.power - vals.power)) from vals left outer join stats on vals.beacon_id=stats.beacon_id group by 1 order by 2 limit 1';
Pages that link here: