1843.(Medium)Suspicious Bank Accounts

Table: Accounts

+----------------+------+
| Column Name    | Type |
+----------------+------+
| account_id     | int  |
| max_income     | int  |
+----------------+------+
account_id is the primary key for this table.
Each row contains information about the maximum monthly income for one bank account.

Table: Transactions

+----------------+----------+
| Column Name    | Type     |
+----------------+----------+
| transaction_id | int      |
| account_id     | int      |
| type           | ENUM     |
| amount         | int      |
| day            | datetime |
+----------------+----------+
transaction_id is the primary key for this table.
Each row contains information about one transaction.
type is ENUM ('Creditor','Debtor') where 'Creditor' means the user deposited money into their account and 'Debtor' means the user withdrew money from their account.
amount is the amount of money depositied/withdrawn during the transaction.

Write an SQL query to report the IDs of all suspicious bank accounts.

A bank account is suspicious if the total income exceeds the max_income for this account for two or more consecutive months. The total income of an account in some month is the sum of all its deposits in that month (i.e., transactions of the type 'Creditor').

Return the result table in ascending order by transaction_id.

The query result format is in the following example:

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/suspicious-bank-accounts

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Solution

刚开始用lag窗口函数,没考虑到有些account的月份之间有间隔。

正确做法是用 PERIOD_DIFF(yyyymm1,yyyymm2),p2)=1 函数self join 真正连续的两个月。

Schema

Last updated

Was this helpful?