mysql 查找所有用户的当前余额,并检查他们是否违反了其信用限额

rjee0c15  于 2022-12-03  发布在  Mysql
关注(0)|答案(3)|浏览(120)

我正在研究这个问题,非常感谢您的帮助!
Question in detail
我将在这里粘贴查询以创建表并在其中添加记录。这样可能更容易测试。

CREATE TABLE user_financial_detail(
id INT PRIMARY KEY,
first_name varchar(20),
last_name varchar(20),
vpa VARCHAR(20),
credit_limit int 
);

CREATE TABLE transaction_log(
id INT PRIMARY KEY,
paid_by VARCHAR(20),
paid_to VARCHAR(20),
amount INT,
transacted_on TIMESTAMP 
);

INSERT INTO user_financial_detail VALUES
(1,'shea','caldwell','sc',5000),
(2,'martena','leblanc','ml',10000),
(3,'tashya','riley','tr',25000);

INSERT INTO transaction_log VALUES
(1,'ml','tr',13155,'2019/11/21'),
(2,'tr','ml',10883,'2019/09/10'),
(3,'sc','tr',15012,'2018/12/25'),
(4,'ml','sc',5700,'2018/05/18'),
(5,'tr','sc',18473,'2018/07/02');

Table layouts

bogh5gae

bogh5gae1#

首先,为每个用户找到平衡:

select vpa, sum(total_amount) balance
from (
  select paid_by vpa, sum(-amount) total_amount
  from transaction_log
  group by paid_by
   union all
  select paid_to vpa, sum(amount) total_amount
  from transaction_log
  group by paid_to
) b
group by vpa

然后将此结果与user_financial_detail连接以获取其余数据:

select 
  concat(u.first_name, ' ',  u.last_name) name, 
  b.vpa, 
  b.balance + u.credit_limit current_balance,
  case
    when b.balance + u.credit_limit >= 0 then 'no'
    else 'yes'
  end credit_limit_breached  
from user_financial_detail u
inner join (
  select vpa, sum(total_amount) balance
  from (
    select paid_by vpa, sum(-amount) total_amount
    from transaction_log
    group by paid_by
     union all
    select paid_to vpa, sum(amount) total_amount
    from transaction_log
    group by paid_to
  ) bi
  group by vpa
) b on b.vpa = u.vpa

结果:

name              vpa      current_balance    credit_limit_breached
shea caldwell     sc       14161                  no
martena leblanc   ml       2028                   no
tashya riley      tr       23811                  no

sxpgvts3

sxpgvts32#

SELECT串接(u.名字,',u.姓氏)名称,
B.VPA,
B.当前余额,
箱型
WHEN B.当前余额〈0
AND Abs(B.当前余额)〉u.credit_限制,则选择“是”
否则“否”
结束 违反信用限额
自 用户财务详细信息u
内部联接(选择vpa、
Sum(总额)当前余额
自 (SELECT付款人 VPA,
Sum(-金额)合计金额
自 事务日志
GROUP BY付款人
所有接头
SELECT收款方 VPA,
Sum(金额)合计_金额
自 事务日志
GROUP BY收款方)bi
分组依据vpa)b
ON B.vpa = u.vpa;

qc6wkl3g

qc6wkl3g3#

信用额为(选择a.vpa,sum(B.amount)作为信用额,来自user_financial_detail作为内部连接交易日志作为b on a.vpa=b.paid_to group by a.vpa)
,借记为(选择A.VPA,SUM(B.金额)作为借记,从user_financial_detail作为内部连接交易日志作为B on A.VPA=B.paid_by Group by A.VPA)
选择a.vpa,(B.贷方-c.借方),当(b.贷方-c.借方)〈0时,则“是”,否则“否”作为内部连接从user_financial_detail结束贷方作为b on a.vpa=b.vpa内部连接借方作为c on a.vpa=c.vpa;

相关问题