select *, ROUND(cast(b.points as decimal) / b.max_points * 100) as percents, AVG(score_five) from group_custom_tests a join custom_tests_results b on a.id = b.custom_test_id where a.group_id = 69 and a.format = 'Вто рой' and b.subject_id = 14 GROUP BY a.id, b.id select distinct on(format) id, format, group_id from group_custom_tests where group_id = 69 select distinct b.subject_id, c.name as subject_name from group_custom_tests a join custom_tests_results b on a.id = custom_test_id join subjects c on b.subject_id = c.id where a.group_id = 69 and a.format = 'Вто рой'