How can I optimize a query with derived tables

welcome to shbcf.ru