SELECT cg.name customer_group,COUNT(t.id) transactions,SUM(t.final_total) revenue,SUM((tsl.unit_price_inc_tax-tsl.unit_price_before_discount)*tsl.quantity) profit FROM customer_groups cg JOIN contacts c ON cg.id=c.customer_group_id JOIN transactions t ON c.id=t.contact_id JOIN transaction_sell_lines tsl ON t.id=tsl.transaction_id WHERE t.type="sell" GROUP BY cg.id,cg.name ORDER BY profit DESC;