力扣高频SQL基础50题详解

前言

力扣的高频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$';
相关推荐
码农-阿杰1 小时前
Java 线程等待唤醒机制深度解析:synchronized、ReentrantLock、LockSupport 底层实现对比
java·开发语言·c++
赤水无泪1 小时前
Qt 全模块汇总列表
开发语言·qt
小虎牙0071 小时前
面试被问复杂度总懵?这篇指南帮你彻底搞清
算法
jran-1 小时前
MySQL多表操作 查询&子查询&外键约束
数据库·mysql
橙子圆1231 小时前
Redis知识6之事务
数据库·redis·缓存
yong99901 小时前
MATLAB仿真计算电磁波回波信号的技术路径与实现指南
开发语言·matlab
不会摸鱼的小鱼1 小时前
WSL 安装 Ubuntu 22.04 到指定磁盘
数据库·postgresql·php
不是光头 强1 小时前
Spring Boot 多线程场景下 i18n 国际化失效问题排查与解决
java·开发语言·springboot
jieyucx1 小时前
Go 语言核心关键字:defer 深度解析与实战避坑
开发语言·后端·golang·defer