mysql - 为什么mysql的答案是错误的?连续登录类似问题
问题描述
问题:
列名 | 类型 |
---|---|
帐户ID | 整数 |
最大收入 | 整数 |
account_id 是该表的主键。每行包含有关一个银行帐户的最大月收入的信息。
表:交易
列名 | 类型 |
---|---|
transaction_id | 整数 |
帐户ID | 整数 |
类型 | 枚举 |
数量 | 整数 |
天 | 约会时间 |
transaction_id 是该表的主键。每一行都包含有关一个事务的信息。类型是 ENUM ('Creditor','Debtor'),其中“Creditor”表示用户将钱存入他们的账户,“Debtor”表示用户从他们的账户中取款。金额是交易期间存入/提取的金额。
编写 SQL 查询以报告所有可疑银行账户的 ID。
如果总收入连续两个或多个月超过此帐户的 max_income,则该银行帐户是可疑的。某个月的账户总收入是该月所有存款的总和(即“贷方”类型的交易)。
按transaction_id升序返回结果表。
查询结果格式如下例:
账户表:
帐户ID | 最大收入 |
---|---|
3 | 21000 |
4 | 10400 |
交易表:
transaction_id | 帐户ID | 类型 | 数量 | 天 |
---|---|---|---|---|
2 | 3 | 债权人 | 107100 | 2021-06-02 11:38:14 |
4 | 4 | 债权人 | 10400 | 2021-06-20 12:39:18 |
11 | 4 | 债务人 | 58800 | 2021-07-23 12:41:55 |
1 | 4 | 债权人 | 49300 | 2021-05-03 16:11:04 |
15 | 3 | 债务人 | 75500 | 2021-05-23 14:40:20 |
10 | 3 | 债权人 | 102100 | 2021-06-15 10:37:16 |
14 | 4 | 债权人 | 56300 | 2021-07-21 12:12:25 |
19 | 4 | 债务人 | 101100 | 2021-05-09 15:21:49 |
8 | 3 | 债权人 | 64900 | 2021-07-26 15:09:56 |
7 | 3 | 债权人 | 90900 | 2021-06-14 11:23:07 |
结果表:
帐户ID |
---|
3 |
对于帐户 3:
- 6-2021年,用户的收入为107100 + 102100 + 90900 = 300100。
- 7-2021年,用户的收入为64900,我们可以看到收入连续两个月超过最高收入21000,所以我们在结果表中加入了3。
对于帐户 4:
- 5-2021年,用户收入4.93万。
- 6-2021年,用户收入10400。
- 7-2021年,用户的收入为56300。我们可以看到,收入超过了5月和7月的最高收入,但6月没有。由于该账户连续两个月没有超过最大收入,我们没有将其包含在结果表中。
在下面写下你的 MySQL 查询语句
select account_id
from (
select account_id, rank() over(partition by account_id order by month) - month diff
from (
select account_id, month
from (
select a.account_id, left(day,7) month, sum(if(type='creditor',amount,0)) income, max_income
from transactions t
join accounts a
on t.account_id = a.account_id
group by a.account_id, left(day,7) ) f1
where income > max_income )f2 )f3
group by account_id, diff
having count(*) >= 2
解决方案
推荐阅读
- linux - Bash 脚本自动通过电子邮件发送变量文件名和相应的修改日期时间戳
- php - 将 MY SQL 查询结果与同一项目 ID 的多行合并为单行以进行 json 响应
- bash - 关于 awk + xxd bash 命令中的 ASCII 换行字节的混淆
- ssl - 我正在研究leadtools并尝试将其配置为在https上工作
- javascript - 日期类型的 Google Visualization CategoryFilter
- python - calendarList().list 未显示所有日历
- laravel - Laravel 种子在数据库中创建错误的行数
- python - 如何检查浏览的文件是 .xlsx 还是 .csv?
- php - Symfony 功能测试 - 如何使用请求模拟控制器注入服务(提交)
- javascript - 控制最后显示插入符号的位置