SQL41 确定最佳顾客的另一种方式(二)

OrderItems 表

  • order_num:订单号
  • item_price:商品单价
  • quantity:商品数量
order_numitem_pricequantity
a110105
a211100
a21200
a421121
a5510
a2119
a775

Orders 表

  • order_num:订单号
  • cust_id:顾客 id
order_numcust_id
a1cust10
a2cust1
a3cust2
a4cust22
a5cust221
a7cust2217

Customers

  • cust_id:顾客 id
  • cust_name:顾客姓名
cust_idcust_name
cust10andy
cust1ben
cust2tony
cust22tom
cust221an
cust2217hex

问题

编写 SQL 语句,返回订单总价不小于1000 的客户名称和总额

示例结果

cust_nametotal_price
andy1050
ben1319
tom2242

分析

第一步:
OrderItems表中找出总额不小于1000的订单号

select
	order_num,
	sum(item_price * quantity) total_price
from OrderItems
group by order_num
having total_price >= 1000

第二步:
Customers表与Orders表进行内连接,之后再与第一步得到的新表进行内连接

select 
from 
	Customers c inner join Orders o
	on c.cust_id = o.cust_id inner join 
		(
			select
				order_num,
				sum(item_price * quantity) total_price
			from OrderItems
			group by order_num
			having total_price >= 1000
		) oi
		on o.order_num = oi.order_num
order by oi.order_num

牛客网:SQL41 确定最佳顾客的另一种方式(二)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值