SELECT c.name,COUNT(t.id) total_visits,COUNT(DISTINCT CASE WHEN vld.qty_available>0 THEN t.id END) successful_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 LEFT JOIN variation_location_details vld ON p.id=vld.product_id WHERE t.type="sell" GROUP BY c.id,c.name ORDER BY successful_purchases DESC;