Using SQL to Find Users with Multiple Daily Payments on the Same Account
This guide demonstrates how to identify users who have made more than one payment on the same day, using the same account number, and with different ZIP codes. We'll use the PAYMENT
table, containing user_id
, account_no
, zip
, and date
columns.
Initial SQL Query:
This query identifies users with multiple payments per day, per account:
<code class="language-sql">SELECT user_id, COUNT(*) AS payment_count FROM PAYMENT GROUP BY account_no, user_id, date HAVING COUNT(*) > 1;</code>
This groups payments by account number, user ID, and date, then filters to show only groups with more than one payment.
Enhanced Query for Distinct ZIP Codes:
To ensure that only users with multiple payments and distinct ZIP codes are identified, we use a subquery:
<code class="language-sql">SELECT user_id, account_no, date, COUNT(*) AS payment_count FROM (SELECT DISTINCT user_id, account_no, zip, date FROM PAYMENT) AS distinct_payments GROUP BY user_id, account_no, date HAVING COUNT(*) > 1;</code>
This subquery (distinct_payments
) first selects unique combinations of user, account, ZIP code, and date. The main query then groups and filters this subset, guaranteeing that only records with multiple payments and distinct ZIP codes are returned. The AS distinct_payments
clause assigns an alias to the subquery for clarity.
The above is the detailed content of How to Identify Users with Multiple Daily Payments on the Same Account Using SQL?. For more information, please follow other related articles on the PHP Chinese website!