SQL必知必会第十一节挑战题

1.使用子查询,返回购买价格为10美元或以上产品的顾客列表。你需要使用OrderItems表查找匹配的订单号(order_num),然后使用Order表检索这些匹配订单的顾客ID(cust_id)。

--1
select cust_id 
from orders 
where order_num in (select order_num from orderitems where item_price >=10)

2.你想知道订购BR01产品的日期。

--2
select cust_id,order_date 
from orders
 where orders.order_num in (select order_num from orderitems where prod_id='BR01')

其中的where语句中的order.加不加无所谓,但为避免歧义,还是加上为好

3.现在我们让它更具挑战性。在上一个挑战题,返回购买prod_id为BR01的产品的所有顾客的电子邮件(Customers表中的cust_email)。提示:这涉及SELECT语句,最内层的从OrderItems表返回order_num,中间的从Customers表返回cust_id。

select cust_email from customers 
where customers.cust_id in  
(select cust_id from orders 
where orders.order_num in
(select order_num from orderitems
where prod_id='BR01'))

        解题思路: 可以先从最内侧的检索order开始,写出每个简答的select语句,最后使用where            和in关键字连接

4.我们需要一个顾客ID列表,其中包含他们已订购的总金额。编写SQL语句,返回顾客ID(Orders表中的cust_id),并使用子查询返回total_ordered以便返回每个顾客的订单总数。将结果按金额从大到小排序。提示:你之前已经使用SUM()计算订单总数。

--4
select orders.cust_id,
(select sum(quantity*item_price) from orderitems where orders.order_num =orderitems.order_num) 
as total_ordered 
from orders 
order by 2

注意:题目最后的排序用数字2代替total-price是方便的,但是不保险

5.再来。编写SQL语句,从Products表中检索所有的产品名称(prod_name),以及名为quant_sold的计算列,其中包含所售产品的总数(在OrderItems表上使用子查询和SUM(quantity)检索)。

select prod_name,
(select sum(quantity) from orderitems where products.prod_id=OrderItems.prod_id) 
as quant_sold
from products

                                                                                                      

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值