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