数据分析sql面试题实战

最近梳理了以前面试遇到的笔试题,跟大家分享一下,都是比较基础的哈
题目一:
表名:购物信息
购物人 商品名称 数量
A 甲 2
B 乙 4
C 丙 1
A 丁 2
B 丙 5
……
找出所有购入商品为两种或两种以上的购物人记录
思路:先找出购入商品为两种或两种以上的购物人,再找出记录,需要使用子查询。
答:

select * from 购物信息 
where 购物人 in 
(select 购物人 
from 购物信息
group by 购物人
having count(*) >= 2)

题目二:
表名:成绩表
姓名 课程 分数
张三 语文 81
张三 数学 75
张三 英语 62
李四 语文 56
李四 数学 90
李四 英语 85
王五 语文 81
王五 数学 100
王五 英语 49

给出成绩全部合格的学生信息(包含姓名、课程、分数),注:分数在60以上评为合格
思路:找出三课成绩都合格的学生或者排除其他学生有某一科成绩不合格的学生。
找出三课成绩都合格即三课成绩最小分数大于等于60:

select * from 成绩表
where 姓名 in 
(select 姓名
from 成绩表
group by 姓名
having min(分数) >=60)

排除其他学生有某一科成绩不合格的学生:

select * from 成绩表
where 姓名
not in
(select
distinct 姓名
from 成绩表 
where 分数 < 60)

题目三:
表名:student
name course score
张青 语文 75
王华 数学 72
张华 英语 81
张青 物理 72
李立 化学 98
张燕 物理 70
张青 化学 80

查询出“张”姓学生中平均成绩大于75分的学生信息(name,course,score),得出学生信息后的score需要从高到低排序
思路:找出“张”姓学生中平均成绩大于75分的学生名字,子查询,按分数排序

select * from student
where name in 
(select name
from student
where name like '张%'
group by name
having avg(score) > 75)
order by score desc

题目四:
A(id,name)表中存在ID重复记录,查询重复3次以上的记录
思路:找出重复三次以上,分组后计数找出ID,再用子查询查出重复的记录

select * from A
where id in 
(select id
from A
group by id
having count(id)>3)

题目五:
在这里插入图片描述
考点:第二高的问题,类似的问题如第二高的人
我这边想到两种思路:
1.找出最高薪水的,然后找出小于最高薪水的薪水

Select max(salary) as SecondHighestSalary  
from employee
Where salary < (Select max(salary) from employee)

2.将工资去重,然后降序排序,取第二个工资

select IFNULL((select Distinct Salary from Employee order by Salary DESC limit 1,1),null) 
as SecondHighestSalary)

题目六:
在这里插入图片描述
考点:一维表转二维表,case when

Select date_format(应还时间,’%Y’-%M’) as 应还月份,
Count(case when 逾期天数>=1 and 逾期天数<30 then id end) as 逾期1天以上,
Count(case when 逾期天数>=30 and 逾期天数<60 then id end) as 逾期30天以上,
Count(case when 逾期天数>=60 then id end) as 逾期60天以上,
Group by 应还月份
Order by 应还月份 desc

以上几题是本人当时面试亲身经历的面试题,有的是后来复盘才想出答案的,当时基础比较差,sql写的少所以不一定能手写的出来,这次作为一次总结复盘,有更好的写法欢迎一起讨论。

猜你喜欢

转载自blog.csdn.net/weixin_43785299/article/details/107239833