SELECT c.name,COUNT(t.id) total_visits,MAX(t.transaction_date) last_visit,DATEDIFF(CURRENT_DATE,MAX(t.transaction_date)) days_since_last_visit FROM contacts c JOIN transactions t ON c.id=t.contact_id WHERE t.type="sell" GROUP BY c.id,c.name ORDER BY days_since_last_visit;