SELECT p.name,COUNT(DISTINCT t.contact_id) total_customers,COUNT(DISTINCT CASE WHEN purchase_count>1 THEN t.contact_id END) returning_customers FROM products p JOIN transaction_sell_lines tsl ON p.id=tsl.product_id JOIN transactions t ON tsl.transaction_id=t.id JOIN (SELECT contact_id,COUNT(*) purchase_count FROM transactions WHERE type="sell" GROUP BY contact_id) pc ON t.contact_id=pc.contact_id WHERE t.type="sell" GROUP BY p.id,p.name ORDER BY returning_customers DESC;