SELECT clients.*, o.total_sales, o.total_refunds, o.avg_ticket, o.num_of_sales FROM "clients" LEFT JOIN (SELECT client_id, SUM(total) FILTER(WHERE type = sales) AS total_sale, SUM(total) FILTER(WHERE type = refunds) AS total_refunds, AVG(total) FILTER(WHERE type = sales) AS avg_ticket, COUNT(*) FILTER(WHERE type = sales) AS total_orders FROM "orders" GROUP BY client_id) o ON o.client_id = clients.id