SQL常见面试题

        今天刷了一遍牛客里的必知必会题,一共50道题,大部分都比较基础,下面汇总一下易错题。

SQL81 顾客登录名

        本题几个关键点:

  • 登录名是其名称和所在城市的组合,因此需要使用substring()和concat()截取和拼接字段。
  • 得到登录名之后需要用upper()转大写。
  • 用as取别名。
select cust_id,cust_name,
upper(concat(substring(cust_name,1,2),substring(cust_city,1,3))) as user_login
from Customers

SQL82 返回 2020 年 1 月的所有订单的订单号和订单日期

        本题筛选条件和日期有关,需要掌握日期相关的查询条件,有两种方式解此题:

# 法一
# 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

SQL86 返回每个订单号各有多少行数

        本题要注意返回的是每个订单号的行数。

select order_num,count(order_num)
from OrderItems 
group by order_num
order by count(order_num) ASC

SQL88 返回订单数量总和不小于100的所有订单的订单号 

        having应在group by 之后。

select order_num
from OrderItems
group by order_num
having sum(quantity)>=100
order by order_num

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

        本题需要注意 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 

SQL108 组合 Products 表中的产品名和 Customers 表中的顾客名

       union与union all 都是行合并,前者去重,后者不去重,会全部罗列出来。他们合并后列数不变,行数变多。UNION 操作符用于合并两个或多个 SELECT 语句的结果集。

select prod_name
from Products
union all 
select cust_name
from Customers
order by prod_name 

SQL109 纠错4

在用 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

相关推荐

  1. Kafka见面试题

    2024-01-02 08:24:03       40 阅读
  2. ZooKeeper见面试题

    2024-01-02 08:24:03       42 阅读
  3. vue见面试题

    2024-01-02 08:24:03       27 阅读
  4. Redis见面试题

    2024-01-02 08:24:03       32 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-02 08:24:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-02 08:24:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-02 08:24:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-02 08:24:03       20 阅读

热门阅读

  1. 服务器安装Mysql5.7

    2024-01-02 08:24:03       40 阅读
  2. 力扣135. 分发糖果

    2024-01-02 08:24:03       35 阅读
  3. python3使用sqlite3构建本地持久化缓存

    2024-01-02 08:24:03       38 阅读
  4. 【PostgreSQL】从零开始:(四十二)系统列

    2024-01-02 08:24:03       32 阅读
  5. 怎么获取客户端真实IP?GO

    2024-01-02 08:24:03       40 阅读