SELECT c.name,COUNT(DISTINCT p.id) unique_products,COUNT(DISTINCT p.category_id) unique_categories 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 WHERE t.type="sell" GROUP BY c.id,c.name ORDER BY unique_categories DESC;