首页 > 解决方案 > 为什么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:

对于帐户 4:

在下面写下你的 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

标签: mysql

解决方案


推荐阅读