SELECT * FROM (
SELECT DISTINCT ON ("complex"."id") "complex".*, "flat".*
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"
ORDER BY "complex"."id", "flat"."price_call"
) q
ORDER BY rate DESC, room_price_min
LIMIT 30