ECNU数据库作业——Lab8

本文介绍了六个SQL查询练习,包括找出既有储蓄又有支票账户的客户、各州客户的账户余额、没有储蓄账户的客户、没有抵押贷款的客户、拥有房贷和车贷的客户以及信用评分低于平均分的客户。
摘要由CSDN通过智能技术生成

Lab 8

1. Find the name of customers who have both saving and checking account types.
SELECT DISTINCT c.cust_name 
FROM customer c 
WHERE EXISTS (
  SELECT 1 FROM customer 
  WHERE cust_ID = c.cust_ID AND acc_type = 'saving'
) AND EXISTS (
    SELECT 1 FROM customer 
    WHERE cust_ID = c.cust_ID AND acc_type = 'checking'
);

使用exists来检查同时存在saving和checking两种账户的用户,运行后发现不存在这样的用户:

image-20231212133116296
2. What are the total account balances for each customer from Utah or Texas?
SELECT c.cust_name, c.state, SUM(c.acc_bal) AS total_balance
FROM customer c
WHERE c.state IN ('Utah', 'Texas')
GROUP BY c.cust_name, c.state;
image-20231212133409108
3. Find the name of customers who do not have an saving account.
SELECT DISTINCT c.cust_name 
FROM customer c 
WHERE NOT EXISTS (SELECT 1 FROM customer 
                  WHERE cust_ID = c.cust_ID AND acc_type = 'saving');

使用NOT EXISTS来检查不存在saving账户的用户,运行结果如下:

image-20231212133916720
4. What are the names of customers who have not taken a Mortage loan?
SELECT DISTINCT c.cust_name
FROM customer c
LEFT JOIN loan l ON c.cust_ID = l.cust_ID AND l.loan_type = 'Mortgages'
WHERE l.loan_ID IS NULL;

采用左连接,将loan_type = 'Mortgages'添加到连接条件中,这样不满足该条件的用户的loan_ID就会为空。运行结果如下:

image-20231212134309959
5. Find the name of customers who have loans of both Mortgages and Auto.
SELECT DISTINCT c.cust_name
FROM customer c
WHERE EXISTS (
    SELECT 1 FROM loan l
    WHERE l.cust_ID = c.cust_ID AND l.loan_type = 'Mortgages'
) AND EXISTS (
    SELECT 1 FROM loan l
    WHERE l.cust_ID = c.cust_ID AND l.loan_type = 'Auto'
);

类似于练习1,采用exists语句来检查同时存在’Mortgages’和’Auto’,运行结果如下:

image-20231212135533910
6. Find the name of customers whose credit score is below the average credit scores of all customers.
SELECT DISTINCT cust_name
FROM customer
WHERE credit_score < (SELECT AVG(credit_score) FROM customer);
image-20231212135734439
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值