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
相关推荐
jiunian_cn3 分钟前
【Redis】数据库管理操作
数据库·redis·缓存
l1t11 分钟前
DeepSeek总结的DuckDB使用 WITH RECURSIVE 和 USING KEY 进行聚合的特性
sql·duckdb
_Johnny_27 分钟前
ETCD 配额/空间告警模拟方案
网络·数据库·etcd
l1t33 分钟前
DeepSeek总结的PostgreSQL解码GIF文件SQL移植到DuckDB的性能优化方法
sql·postgresql·性能优化
猫头虎40 分钟前
基于信创openEuler系统安装部署OpenTeleDB开源数据库的实战教程
数据库·redis·sql·mysql·开源·nosql·database
爬山算法44 分钟前
MongoDB(1)什么是MongoDB?
数据库·mongodb
Nandeska1 小时前
17、MySQL InnoDB ReplicaSet
数据库·mysql
AI_56781 小时前
SQL性能优化全景指南:从量子执行计划到自适应索引的终极实践
数据库·人工智能·学习·adb
kali-Myon1 小时前
2025春秋杯网络安全联赛冬季赛-day1
java·sql·安全·web安全·ai·php·web
数据知道1 小时前
PostgreSQL 性能优化:分区表实战
数据库·postgresql·性能优化