SELECT c.name,COUNT(DISTINCT t.id) transactions,SUM(t.final_total) total_spent,COUNT(DISTINCT t2.contact_id) referred_customers FROM contacts c JOIN transactions t ON c.id=t.contact_id LEFT JOIN transactions t2 ON t.transaction_date<t2.transaction_date WHERE t.type="sell" GROUP BY c.id,c.name ORDER BY referred_customers DESC;