SELECT c.name,AVG(CASE WHEN tsl.line_discount_amount>0 THEN 1 ELSE 0 END) discount_rate,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 WHERE t.type="sell" GROUP BY c.id,c.name ORDER BY discount_rate DESC;