SELECT id, link, name, hours_together, coef FROM ( SELECT my_users.user_id, COUNT (*)::float / 12 AS hours_together, COUNT(*)::float / user_coef.their_hours AS coef FROM online{$current_user} LEFT JOIN online{$current_user} AS my_users ON my_users.status = online{$current_user}.status INNER JOIN (SELECT user_id, COUNT(*) AS their_hours FROM online{$current_user} GROUP BY user_id) AS user_coef ON user_coef.user_id = my_users.user_id WHERE online{$current_user}.user_id = {$user} GROUP BY online{$current_user}.user_id, my_users.user_id, user_coef.their_hours ORDER BY hours_together DESC ) AS my_comp JOIN users{$current_user} ON (my_comp.user_id = id);