select
*
from
(
SELECT
flat.*,
row_number() over (partition by complex.id order by complex.rate DESC, flat.price_call, complex.room_price_min) as nn
FROM flat
LEFT JOIN complex ON flat.complex_id = complex.id
LEFT JOIN building ON flat.building_id = building.id
LEFT JOIN section ON flat.section_id = section.id
) as x
where x.nn = 1
LIMIT 30;