SELECT c.name,COUNT(DISTINCT CASE WHEN DATEDIFF(t.transaction_date,p.created_at)<30 THEN p.id END) new_products_bought 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 WHERE t.type="sell" GROUP BY c.id,c.name ORDER BY new_products_bought DESC;