SELECT cg.name segment,COUNT(DISTINCT c.id) customers,SUM(t.final_total) revenue,SUM(t.final_total)/COUNT(DISTINCT c.id) avg_revenue_per_customer FROM customer_groups cg JOIN contacts c ON cg.id=c.customer_group_id JOIN transactions t ON c.id=t.contact_id WHERE t.type="sell" GROUP BY cg.id,cg.name ORDER BY avg_revenue_per_customer DESC;