SQL常见面试题

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

SQL81 顾客登录名

本题几个关键点:

  • 登录名是其名称和所在城市的组合,因此需要使用substring()和concat()截取和拼接字段。
  • 得到登录名之后需要用upper()转大写。
  • 用as取别名。
sql 复制代码
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 月的所有订单的订单号和订单日期

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

sql 复制代码
# 法一
# 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 返回每个订单号各有多少行数

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

sql 复制代码
select order_num,count(order_num)
from OrderItems 
group by order_num
order by count(order_num) ASC

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

having应在group by 之后。

sql 复制代码
select order_num
from OrderItems
group by order_num
having sum(quantity)>=100
order by order_num

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

本题需要注意 HAVING 子句在聚合之后筛选结果。

sql 复制代码
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 语句的结果集。

sql 复制代码
select prod_name
from Products
union all 
select cust_name
from Customers
order by prod_name 

SQL109 纠错4

在用 UNION 组合查询时,只能使用一条 ORDER BY 子句,它必须出现在最后一条 SELECT 语句之后。对于结果集,不存在用一种方式排序一部分,而又用另一种方式排序另一部分的情况,因此不允许使用多条 ORDER BY 子句。

sql 复制代码
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
相关推荐
飞将2 小时前
从零实现数据库(2)——HashIndex + IndexManager
数据库
Nturmoils1 天前
订单列表慢查询,先看 WHERE、ORDER BY 和 LIMIT
数据库
渣波1 天前
拒绝 SQL 焦虑!手把手带你用 NestJS + Prisma + DTO 写出“防弹”级后端代码
javascript·数据库·后端
倔强的石头_2 天前
KingbaseES 新版MySQL 兼容版体验:旧版迁移 + 功能实测
数据库
zzzzzz3103 天前
9K Star 炸裂开源!这个 C 语言写的代码知识图谱,把 Linux 内核索引压缩到了 3 分钟
linux·服务器·sql
倔强的石头_5 天前
《Kingbase护城河》——数据库存储空间全景探测与精细化瘦身实战
数据库
云技纵横5 天前
唯一索引 INSERT 死锁实战:5 秒复现交叉插入的 S 锁循环等待
sql·mysql
冬奇Lab6 天前
每日一个开源项目(第134篇):Zvec - 阿里开源的嵌入式向量数据库,向量搜索界的 SQLite
数据库·人工智能·llm
ClouGence6 天前
Oracle CDC 架构优化:从主库直连到 DataGuard 备库同步
数据库·后端·oracle
无响应de神6 天前
三、用户与权限管理
数据库·mysql