You are given two tables: Accounts and Transactions.
The Accounts table contains information about maximum monthly income for each bank account:
account_id- unique identifier for each accountmax_income- maximum allowed monthly income
The Transactions table contains transaction details:
transaction_id- unique identifier for each transactionaccount_id- account involved in the transactiontype- either 'Creditor' (deposit) or 'Debtor' (withdrawal)amount- transaction amountday- transaction date
A bank account is suspicious if the total income exceeds the max_income for two or more consecutive months. The total income is the sum of all 'Creditor' transactions in that month.
Write a SQL query to find all suspicious bank accounts.
Table Schema
| Column Name | Type | Description |
|---|---|---|
account_id
PK
|
int | Unique identifier for each bank account |
max_income
|
int | Maximum allowed monthly income for this account |
| Column Name | Type | Description |
|---|---|---|
transaction_id
PK
|
int | Unique identifier for each transaction |
account_id
|
int | Account involved in the transaction |
type
|
ENUM | Transaction type: 'Creditor' (deposit) or 'Debtor' (withdrawal) |
amount
|
int | Transaction amount |
day
|
datetime | Date when transaction occurred |
Input & Output
| account_id | max_income |
|---|---|
| 1 | 4000 |
| 2 | 3000 |
| transaction_id | account_id | type | amount | day |
|---|---|---|---|---|
| 1 | 1 | Creditor | 2500 | 2021-01-02 |
| 2 | 1 | Creditor | 2000 | 2021-01-15 |
| 3 | 1 | Creditor | 3000 | 2021-02-05 |
| 4 | 1 | Creditor | 2000 | 2021-02-20 |
| 5 | 2 | Creditor | 2000 | 2021-01-10 |
| account_id |
|---|
| 1 |
Account 1 has total income of 4500 in January (2500+2000) and 5000 in February (3000+2000), both exceeding the max_income of 4000 for consecutive months. Account 2 only has 2000 in January, which doesn't exceed its limit of 3000.
| account_id | max_income |
|---|---|
| 3 | 3000 |
| transaction_id | account_id | type | amount | day |
|---|---|---|---|---|
| 6 | 3 | Creditor | 4000 | 2021-01-05 |
| 7 | 3 | Creditor | 1000 | 2021-02-10 |
| 8 | 3 | Creditor | 4000 | 2021-03-15 |
| account_id |
|---|
Account 3 exceeds its limit in January (4000 > 3000) and March (4000 > 3000), but not in February (1000 < 3000). Since the violations are not consecutive, this account is not suspicious.
Constraints
-
1 ≤ account_id ≤ 10000 -
1 ≤ max_income ≤ 1000000 -
typeis either'Creditor'or'Debtor' -
1 ≤ amount ≤ 100000 -
dayis a valid datetime