LeetCode solutions

4025. Find Loyal Customers

My accepted SQL solution to LeetCode problem 4025, Find Loyal Customers, running in 285ms.

  • Difficulty: Medium
  • SQL
  • Runtime 285ms
  • Memory 0.0B

Read the problem on LeetCode View on GitHub

SQL

Accepted on LeetCode — runtime 285ms, memory 0.0B, accepted 2026-01-02.

sql
SELECT customer_id
FROM customer_transactions
GROUP BY customer_id
HAVING 
    SUM(CASE WHEN transaction_type = 'purchase' THEN 1 ELSE 0 END) >= 3
        AND DATEDIFF(MAX(transaction_date), MIN(transaction_date)) >= 30
            AND SUM(CASE WHEN transaction_type = 'refund' THEN 1 ELSE 0 END) * 1.0 / COUNT(*) < 0.2
            ORDER BY customer_id;

Source