首页 > 试题广场 >

用户交易金额查询

[编程题]用户交易金额查询
  • 热度指数:81 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解

金融业务时,通常会涉及客户、账户和交易等表格。下面是对这三个表中字段的一般意义的描述:

客户表 (customers)

  • customer_id: 客户的唯一标识符
  • customer_name: 客户的姓名
  • date_of_birth:出生日期
  • email:邮箱信息

账户表 (accounts)

  • account_id: 账户的唯一标识符
  • customer_id: 与客户表关联的外键,表示该账户属于哪个客户
  • account_type:账户类型
  • balance: 账户的当前余额
  • open_date:开卡日期

交易表 (transactions)

  • transaction_id: 交易的唯一标识符
  • account_id: 与账户表关联的外键,表示该交易涉及的账户
  • amount: 交易金额
  • transaction_type: 交易类型,比如存款、取款、转账等
  • transaction_date: 交易日期
查询要求:
需要查询出有存款或取款记录的客户的账户余额总和,以及他们在2023年内的存款总额、取款总额和平均每月存款和取款金额。(所有金额保留两位小数,查出多个存取款的客户按照客户ID升序排列)
  • customer_id:有存取款记录的客户的唯一标识符
  • customer_name:有存取款记录的客户的姓名
  • total_balance:有存取款记录的客户所有账户总余额,例如Alice Johnson有两个账户余额分别是5000.00和2000.00,所以该用户账户的余额总金额是7000.00
  • total_deposit:有存取款记录的客户2023年的所有账户下存款总额,例如2023年Alice Johnson分别有两笔存款交易1001和1003,两笔存款总金额是1500.00
  • total_withdrawal:有存取款记录的客户2023年的所有账户下取款总额,例如2023年Alice Johnson分别有三笔取款交易1002和1004、1005,三笔取款总金额是600.00
  • avg_monthly_deposit:有存取款记录的客户2023年平均月存款金额,例如2023Alice Johnson总存款金额是1500.00,平均每月的存款金额为1500.00/12 == 125.00
  • avg_monthly_withdrawal:有存取款记录的客户2023年平均月取款金额,例如2023Alice Johnson总取款金额是600.00,平均每月的存款金额为600.00/12 == 50.00


示例1

输入

drop table if exists customers;
drop table if exists accounts;
drop table if exists transactions;
CREATE TABLE customers (
    customer_id INT PRIMARY KEY,
    customer_name VARCHAR(100),
    date_of_birth DATE,
    email VARCHAR(100)
);
CREATE TABLE accounts (
    account_id INT PRIMARY KEY,
    customer_id INT,
    account_type VARCHAR(50),
    balance DECIMAL(15, 2),
    open_date DATE
);
CREATE TABLE transactions (
    transaction_id INT PRIMARY KEY,
    account_id INT,
    transaction_date DATE,
    amount DECIMAL(10, 2),
    transaction_type VARCHAR(50)
);
INSERT INTO customers (customer_id, customer_name, date_of_birth, email) VALUES
(1, 'Alice Johnson', '1990-05-15', 'alice@example.com'),
(2, 'Bob Smith', '1985-08-20', 'bob@example.com');

INSERT INTO accounts (account_id, customer_id, account_type, balance, open_date) VALUES
(101, 1, 'Savings', 5000.00, '2019-01-10'),
(102, 1, 'Checking', 2000.00, '2020-03-15'),
(103, 2, 'Savings', 8000.00, '2018-06-20'),
(104, 2, 'Checking', 4000.00, '2019-02-25');

INSERT INTO transactions (transaction_id, account_id, transaction_date, amount, transaction_type) VALUES
(1001, 101, '2023-01-15', 500.00, 'Deposit'),
(1002, 102, '2023-02-10', -200.00, 'Withdrawal'),
(1003, 101, '2023-03-05', 1000.00, 'Deposit'),
(1004, 102, '2023-03-20', -100.00, 'Withdrawal'),
(1005, 101, '2023-04-02', -300.00, 'Withdrawal');

输出

customer_id|customer_name|total_balance|total_deposit|total_withdrawal|avg_monthly_deposit|avg_monthly_withdrawal
1|Alice Johnson|7000.00|1500.00|600.00|125.00|50.00

这道题你会答吗?花几分钟告诉大家答案吧!