SELECT c.name category,SUM((tsl.unit_price_inc_tax-pl.purchase_price)*tsl.quantity) profit,SUM(pl.purchase_price*pl.quantity) investment,(SUM((tsl.unit_price_inc_tax-pl.purchase_price)*tsl.quantity)/NULLIF(SUM(pl.purchase_price*pl.quantity),0))*100 roi FROM categories c JOIN products p ON c.id=p.category_id JOIN purchase_lines pl ON p.id=pl.product_id JOIN transaction_sell_lines tsl ON p.id=tsl.product_id JOIN transactions t ON tsl.transaction_id=t.id WHERE t.type="sell" GROUP BY c.id,c.name ORDER BY roi DESC;