SELECT c.name,COUNT(DISTINCT CASE WHEN t.type="sell_return" THEN t.id END) complaints,COUNT(DISTINCT CASE WHEN t.type="sell" THEN t.id END) purchases,MAX(t.transaction_date) last_purchase FROM contacts c JOIN transactions t ON c.id=t.contact_id GROUP BY c.id,c.name HAVING complaints>0 ORDER BY DATEDIFF(CURRENT_DATE,last_purchase);