MySQL高阶2066-账户余额

目录

题目

准备数据

分析数据

总结


题目

请写出能够返回用户每次交易完成后的账户余额. 我们约定所有用户在进行交易前的账户余额都为0, 并且保证所有交易行为后的余额不为负数。

返回的结果请依次按照 账户(account_id), 日期( day ) 进行升序排序 .

准备数据

Create table If Not Exists Transactions (account_id int, day date, type ENUM('Deposit', 'Withdraw'), amount int)
    Truncate table Transactions
    insert into Transactions (account_id, day, type, amount) values ('1', '2021-11-07', 'Deposit', '2000')
    insert into Transactions (account_id, day, type, amount) values ('1', '2021-11-09', 'Withdraw', '1000')
    insert into Transactions (account_id, day, type, amount) values ('1', '2021-11-11', 'Deposit', '3000')
    insert into Transactions (account_id, day, type, amount) values ('2', '2021-12-07', 'Deposit', '7000')
    insert into Transactions (account_id, day, type, amount) values ('2', '2021-12-12', 'Withdraw', '7000')

分析数据

select
    account_id, day,
    sum(case when type = 'Deposit' then amount else -amount end) over (partition by account_id order by day) balance
from
    transactions
order by
    account_id,day;

总结

使用开窗函数sum()计算不同的交易类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值