今天刷了一遍牛客里的必知必会题,一共50道题,大部分都比较基础,下面汇总一下易错题。
本题几个关键点:
select cust_id,cust_name, upper(concat(substring(cust_name,1,2),substring(cust_city,1,3))) as user_login from Customers
本题筛选条件和日期有关,需要掌握日期相关的查询条件,有两种方式解此题:
# 法一 # select order_num,order_date # from Orders # where order_date like '2020-01-%' # order by order_date ASC # 法二 select order_num,order_date from Orders where YEAR(order_date)='2020' and MONTH(order_date)='01' order by order_date ASC
本题要注意返回的是每个订单号的行数。
select order_num,count(order_num) from OrderItems group by order_num order by count(order_num) ASC
having应在group by 之后。
select order_num from OrderItems group by order_num having sum(quantity)>=100 order by order_num
本题需要注意 HAVING 子句在聚合之后筛选结果。
select cust_name,sum(item_price*quantity) as total_price from OrderItems inner join Orders on OrderItems.order_num=Orders.order_num inner join Customers on Orders.cust_id=Customers.cust_id group by cust_name having total_price>=100 order by total_price
union与union all 都是行合并,前者去重,后者不去重,会全部罗列出来。他们合并后列数不变,行数变多。UNION 操作符用于合并两个或多个 SELECT 语句的结果集。
select prod_name from Products union all select cust_name from Customers order by prod_name
在用 UNION 组合查询时,只能使用一条 ORDER BY 子句,它必须出现在最后一条 SELECT 语句之后。对于结果集,不存在用一种方式排序一部分,而又用另一种方式排序另一部分的情况,因此不允许使用多条 ORDER BY 子句。
SELECT cust_name, cust_contact, cust_email FROM Customers WHERE cust_state = 'MI' UNION SELECT cust_name, cust_contact, cust_email FROM Customers WHERE cust_state = 'IL' ORDER BY cust_name