Leetcode Problem 1843. Suspicious Bank Accounts

1843. Suspicious Bank Accounts

Leetcode Solutions

MySQL CTE and PERIOD_DIFF

  1. Create a CTE (temp) to calculate the total income per month for each account by summing up the amounts of 'Creditor' transactions grouped by account and month.
  2. Join the temp CTE with the Accounts table to filter out the months where the income does not exceed the max_income.
  3. Use a self-join on the temp CTE to find pairs of rows with the same account_id and consecutive months (using PERIOD_DIFF).
  4. Group by account_id and select the accounts that appear more than once, indicating at least two consecutive months of exceeding max_income.
  5. Return the distinct account_ids of the suspicious accounts.

erDiagram
    Accounts {
        int account_id
        int max_income
    }
    Transactions {
        int transaction_id
        int account_id
        enum type
        int amount
        datetime day
    }
    Accounts ||--o{ Transactions : has

MySQL CTE with Year-Month Grouping and Self-Join

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...