SQL刷题小计
SQL刷题小计
确定哪些订单购买了 prod_id 为 BR01 的产品(2)
这个题可以采用子查询和联合查询
子查询
# 先在第一张表当中查询出id为BRO1的数据然后再将这个数据放在第二张表当中查询
select order_num from orderitems where prod_id='BR01';
select cust_id,order_date from Orders where order_num in (select order_num from OrderItems where prod_id='BR01') order by order_date;
联合查询
# 联合查询 让o1.prod_id='BR01' 并且o2.order_num=o1.order_num 就行
select o2.cust_id,o2.order_date from OrderItems o1,Orders o2 where o1.prod_id='BR01' AND o2.order_num=o1.order_num order by o2.order_date;
返回顾客名称和相关订单号以及每个订单的总价
3个表格联合查询
select c.cust_name, o.order_num, o2.quantity*o2.item_price as OrderTotal -- 这里注意计算最后的价格
from Customers c,
Orders o,
OrderItems o2
where c.cust_id = o.cust_id -- 注意查询的条件
and o2.order_num = o.order_num order by c.cust_name,o.order_num;
确定最佳顾客的另一种方式(二)
这个题有点难度,不太会
SQL104返回产品名称和每一项产品的总订单数
SQL30 统计每种性别的人数
这个题注意掌握SQL中if 语句的用法以及自定义分组查询的用法.
select if(profile like '%female', 'female', 'male') gender, count(*) number
# 先使用if判断profile中是否存在female 如果存在就返回female 否则返回male ,然后以这个进行分组,进行count统计
from user_submit
group by gender;
下面来使用SUBSTRING_INDEX函数解题
SUBSTRING_INDEX函数介绍
select substring_index(profile,',',-1) gender,count(*) number from user_submit group by gender;
# 先使用substring_index分割出来是人员是哪一种性别,然后进行分组,然后就和上面的一样了