返回介绍

solution / 2000-2099 / 2066.Account Balance / README_EN

发布于 2024-06-17 01:03:11 字数 2927 浏览 0 评论 0 收藏 0

2066. Account Balance

中文文档

Description

Table: Transactions

+-------------+------+
| Column Name | Type |
+-------------+------+
| account_id  | int  |
| day     | date |
| type    | ENUM |
| amount    | int  |
+-------------+------+
(account_id, day) is the primary key (combination of columns with unique values) for this table.
Each row contains information about one transaction, including the transaction type, the day it occurred on, and the amount.
type is an ENUM (category) of the type ('Deposit','Withdraw') 

 

Write a solution to report the balance of each user after each transaction. You may assume that the balance of each account before any transaction is 0 and that the balance will never be below 0 at any moment.

Return the result table in ascending order by account_id, then by day in case of a tie.

The result format is in the following example.

 

Example 1:

Input: 
Transactions table:
+------------+------------+----------+--------+
| account_id | day    | type   | amount |
+------------+------------+----------+--------+
| 1      | 2021-11-07 | Deposit  | 2000   |
| 1      | 2021-11-09 | Withdraw | 1000   |
| 1      | 2021-11-11 | Deposit  | 3000   |
| 2      | 2021-12-07 | Deposit  | 7000   |
| 2      | 2021-12-12 | Withdraw | 7000   |
+------------+------------+----------+--------+
Output: 
+------------+------------+---------+
| account_id | day    | balance |
+------------+------------+---------+
| 1      | 2021-11-07 | 2000  |
| 1      | 2021-11-09 | 1000  |
| 1      | 2021-11-11 | 4000  |
| 2      | 2021-12-07 | 7000  |
| 2      | 2021-12-12 | 0     |
+------------+------------+---------+
Explanation: 
Account 1:
- Initial balance is 0.
- 2021-11-07 --> deposit 2000. Balance is 0 + 2000 = 2000.
- 2021-11-09 --> withdraw 1000. Balance is 2000 - 1000 = 1000.
- 2021-11-11 --> deposit 3000. Balance is 1000 + 3000 = 4000.
Account 2:
- Initial balance is 0.
- 2021-12-07 --> deposit 7000. Balance is 0 + 7000 = 7000.
- 2021-12-12 --> withdraw 7000. Balance is 7000 - 7000 = 0.

Solutions

Solution 1

# Write your MySQL query statement below
SELECT
  account_id,
  day,
  SUM(IF(type = 'Deposit', amount, -amount)) OVER (
    PARTITION BY account_id
    ORDER BY day
  ) AS balance
FROM Transactions
ORDER BY 1, 2;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文