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