SELECT c.name,COUNT(DISTINCT b.id) brands_purchased,COUNT(t.id) total_purchases FROM contacts c JOIN transactions t ON c.id=t.contact_id JOIN transaction_sell_lines tsl ON t.id=tsl.transaction_id JOIN products p ON tsl.product_id=p.id JOIN brands b ON p.brand_id=b.id WHERE t.type="sell" GROUP BY c.id,c.name ORDER BY brands_purchased DESC;