前言
力扣的高频SQL基础题和进阶题刷完之后,基本上能够应对全部中小厂和部分大厂,主要根据学历而定,学历高的面试时很多情况下都是不会太针对你的,学历低的话就要做好面对难题的准备。但是低学历的同学们也不要害怕,这种情况也不会太常见,所以不管我们到时候会遇到什么,只要自己去好好刷过几轮也不会太慌,它不可能全是难题。
高频SQL50题(基础版)

1757. 可回收且低脂的产品
sql
SELECT product_id
FROM Products
WHERE low_fats='Y' and recyclable='Y';
584. 寻找用户推荐人
sql
select name
from Customer
where referee_id != 2 or referee_id is null
595. 大的国家
sql
select name,population,area
from World
where area>=3000000 or population>=25000000
1148. 文章浏览 I
sql
select distinct author_id as id
from Views
where author_id=viewer_id
order by id
1683. 无效的推文
sql
select tweet_id
from Tweets
where length(content)>15
1378. 使用唯一标识码替换员工ID
sql
select unique_id,name
from Employees left join EmployeeUNI
on EmployeeUNI.ID=Employees.ID
1068. 产品销售分析 I
sql
select product_name,year,price
from Sales join Product
on Sales.product_id = Product.product_id
1581. 进店却未进行过交易的顾客
sql
select customer_id, count(*) as count_no_trans
from Visits v left join Transactions t on
v.visit_id = t.visit_id
where transaction_id is null
group by customer_id
197. 上升的温度
sql
select w2.id id
from Weather w1 join Weather w2
on w1.recordDate = w2.recordDate-interval 1 day
where w1.Temperature < w2.Temperature
1661. 每台机器的进程平均运行时间
sql
# 运行时间17%
select start.machine_id, round(avg(end.timestamp-start.timestamp),3) processing_time
from
(select *
from Activity
where activity_type ='start') as start
join
(select *
from Activity
where activity_type ='end') as end
on
start.machine_id=end.machine_id and start.process_id=end.process_id
group by start.machine_id
sql
# 运行时间45%
select machine_id,
round((2*sum(timestamp*(case when activity_type = 'start' then -1 else 1 end)))/count(activity_type),3) as processing_time
from Activity
group by machine_id
577. 员工奖金
sql
select name,bonus
from Employee left join Bonus
on Employee.empId = Bonus.empid
where bonus<1000 or bonus is null
1280. 学生们参加各科测试的次数
sql
select a.student_id,a.student_name,a.subject_name,ifnull(attended_exams,0) attended_exams
from
(select *
from subjects join students) a
left join
(select *,count(e.student_id) as attended_exams
from Examinations e
group by e.student_id,e.subject_name) b
on a.student_id = b.student_id
and a.subject_name = b.subject_name
order by a.student_id,a.subject_name
570. 至少有5名直接下属的经理
sql
select e2.name name
from Employee e2
left join Employee e1
on e1.managerId=e2.id
group by e2.id
having count(*)>=5
1934. 确认率
sql
select s.user_id,round(sum(if(action='confirmed',1,0))/count(*),2) confirmation_rate
from Signups s
left join Confirmations c
on s.user_id = c.user_id
group by s.user_id
620. 有趣的电影
sql
select *
from cinema
where description!='boring' and id%2!=0
order by rating desc
1251. 平均售价
sql
select p.product_id,ifnull(round((sum(price*units)/sum(units)),2),0) as average_price
from Prices p left join UnitsSold u
on p.product_id = u.product_id
and u.purchase_date between p.start_date and p.end_date
group by p.product_id
1075. 项目员工 I
sql
select project_id,round(avg(experience_years),2) as average_years
from Project p left join Employee e
on p.employee_id = e.employee_id
group by project_id
1633. 各赛事的用户注册率
sql
select contest_id,round(count(contest_id)/(select count(*) from Users)*100,2) as percentage
from Register r left join Users u
on r.user_id = u.user_id
group by contest_id
order by percentage desc,contest_id
1211. 查询结果的质量和占比
sql
select query_name,round(avg(rating/position),2) as quality,
round((100*sum(case when rating<3 then 1 else 0 end)/count(*)),2) as poor_query_percentage
from Queries
group by query_name
having query_name is not null
1193. 每月交易 I
sql
select left(trans_date,7) as month,
country,count(*) as trans_count,
sum(case when state='approved' then 1 else 0 end) as approved_count,
sum(amount) as trans_total_amount,
sum((case when state='approved' then 1 else 0 end)*amount) as approved_total_amount
from Transactions
group by month,country
1174. 即时食物配送 II
sql
select round((sum(case when customer_pref_delivery_date=order_date then 1 else 0 end)*100/count(*)),2) as immediate_percentage
from
(select customer_id,min(order_date) as order_date,min(customer_pref_delivery_date) as customer_pref_delivery_date
from Delivery
group by customer_id) as first_order
550. 游戏玩法分析 IV
sql
# 卡了很久最小时间
select round(count(*)/(select count(distinct player_id) from Activity),2) as fraction
from
((select player_id,min(event_date) as event_date
from Activity
group by player_id) as a1
join Activity a2
on a1.player_id=a2.player_id
and a1.event_date=a2.event_date - interval 1 day)
2356. 每位教师所教授的科目种类的数量
sql
select teacher_id,count(distinct subject_id) as cnt
from teacher
group by teacher_id
1141. 查询近30天活跃用户数
sql
select activity_date as day,count(distinct user_id) as active_users
from Activity
group by activity_date
having activity_date between ("2019-07-27"- interval 29 day) and "2019-07-27"
1084. 销售分析III
sql
# 注意sum=count的用法,用于"所有都是......"的场景
select s.product_id,product_name
from Sales s left join Product p
on s.product_id=p.product_id
group by s.product_id
having sum(s.sale_date between "2019-01-01" and "2019-03-31")=count(*)
596. 超过5名学生的课
sql
select class
from Courses
group by class
having count(*)>=5
1729. 求关注者的数量
sql
select user_id,count(*) as followers_count
from Followers
group by user_id
order by user_id
619. 只出现一次的最大数字
sql
select max(num) num
from
(select num
from MyNumbers
group by num
having count(*)=1) num1
1045. 买下所有产品的客户
sql
select customer_id
from Customer
group by customer_id
having count(distinct product_key)= (select count(*) from Product)
1731. 每位经理的下属员工数量
sql
select e2.employee_id,e2.name,count(*) as reports_count,
round(avg(e1.age),0) as average_age
from Employees e1 left join Employees e2
on e1.reports_to = e2.employee_id
group by e2.employee_id
having e2.employee_id is not null
order by employee_id
1789. 员工的直属部门
sql
(select employee_id,department_id
from Employee
where primary_flag ='Y')
UNION
(select employee_id,department_id
from Employee
group by employee_id
having count(*)=1)
order by employee_id
610. 判断三角形
sql
select *,
(case when (x+y>z and x+z>y and z+y>x) then "Yes"
else "No"
end) as triangle
from Triangle
180. 连续出现的数字
sql
select distinct L1.num as ConsecutiveNums
from Logs L1
join Logs L2 on L1.id=L2.id-1
join Logs L3 on L2.id=L3.id-1
where L1.num=L2.num and L2.num=L3.num
1164. 指定日期的产品价格
sql
select product_id, new_price as price
from Products
where (product_id,change_date) in
(select product_id,max(change_date)
from Products
where change_date<="2019-08-16"
group by product_id)
union
select product_id,10 as price
from Products
where product_id not in (select product_id from Products where change_date<="2019-08-16")
1204. 最后一个能进入巴士的人
sql
select q1.person_name
from Queue q1
join Queue q2 on q1.turn>=q2.turn
group by q1.person_id
having sum(q2.weight)<=1000
order by q1.turn desc limit 1
1907. 按分类统计薪水
sql
select "Low Salary" category,count(*) accounts_count
from Accounts
where income<20000
union
select "Average Salary" category,count(*) accounts_count
from Accounts
where income between 20000 and 50000
union
select "High Salary" category,count(*) accounts_count
from Accounts
where income>50000
1978. 上级经理已离职的公司员工
sql
select employee_id
from Employees
where salary<30000 and manager_id not in (select employee_id from Employees)
order by employee_id
626. 换座位
sql
select
(case when id%2!=0 and id!=(select count(*) from Seat) then id+1
when id%2=0 then id-1
else id end) as id,student
from Seat
order by id
1341. 电影评分
sql
(select name as results
from Users u
join MovieRating r1 on u.user_id = r1.user_id
group by u.user_id
order by count(*) desc,name limit 1)
union all
(select title as results
from Movies m
join MovieRating r2 on m.movie_id = r2.movie_id and left(r2.created_at,7) = "2020-02"
group by r2.movie_id
order by avg(rating) desc,title limit 1)
1321. 餐馆营业额变化增长
sql
#注意join时where的用法以及分组之后avg函数的使用
select a.visited_on,sum(c.amount) as amount,round((sum(c.amount))/7,2) as average_amount
from
(select distinct visited_on
from Customer) as a
left join customer c
on (c.visited_on>=a.visited_on - interval 6 day) and (c.visited_on<=a.visited_on)
where a.visited_on>=(select min(visited_on) from customer)+6
group by a.visited_on
order by a.visited_on
602. 好友申请 II :谁有最多的好友
sql
select a.id,count(*) as num
from
(select requester_id as id from RequestAccepted r1
union all
select accepter_id as id from RequestAccepted r2) as a
group by id
order by num desc limit 1
585. 2016年的投资
sql
select round(sum(tiv_2016),2) tiv_2016
from Insurance
where tiv_2015 in
(select tiv_2015 from Insurance
group by tiv_2015 having count(*)>1)
and concat(lat, lon) in
(select concat(lat, lon)
from Insurance
group by concat(lat, lon)
having count(*)=1)
185. 部门工资前三高的所有员工
sql
select d.name as Department,e.name as Employee,e.salary
from Employee e left join Department d
on e.departmentId=d.id
where e.id in
(select e1.id
from Employee e1 left join Employee e2
on e1.departmentId=e2.departmentId and e1.salary<e2.salary
group by e1.id
having count(distinct e2.salary)<=2)
1667. 修复表中的名字
sql
select user_id,concat(upper(left(name,1)),lower(SUBSTRING(name,2))) name
from Users
order by user_id
1527. 患某种疾病的患者
sql
select *
from Patients
where conditions like "DIAB1%" or conditions like "% DIAB1%"
196. 删除重复的电子邮箱
sql
delete from
Person
where id not in
(select id from(select min(id) id
from Person
group by email) as a)
176. 第二高的薪水
sql
select ifnull((
select distinct salary
from Employee
order by salary desc
limit 1 offset 1),null) as SecondHighestSalary
1484. 按日期分组销售产品
sql
select sell_date,count(distinct product) as num_sold,
group_concat(distinct product order by product SEPARATOR ',') as products
from Activities
group by sell_date
order by sell_date
1327. 列出指定时间段内所有的下单产品
sql
select product_name,sum(unit) as unit
from Products p join Orders o
on p.product_id=o.product_id and left(o.order_date,7)="2020-02"
group by product_name
having sum(unit)>=100
1517. 查找拥有有效邮箱的用户
sql
SELECT user_id, name, mail
FROM Users
WHERE mail REGEXP '^[a-zA-Z][a-zA-Z0-9_.-]*\\@leetcode\\.com$';