以下内容,是本人做牛客网数据库SQL实战中的一些总结技巧和常见错误,若有不正确的地方,欢迎留言探讨,非常感谢!
SQL篇链接:https://www.nowcoder.com/exam/oj?page=1&tab=SQL%E7%AF%87&topicId=199
条件查询
基础操作符
SQL9 基础操作符
题目:现在运营想要查看除复旦大学以外的所有用户明细,请你取出相应数据
select
device_id,gender,age,university
from user_profile
where not university ="复旦大学"
技巧:该题除了使用逻辑运算符NOT,还可以使用比较运算符 != ,语句如下
select
device_id,gender,age,university
from user_profile
where university != "复旦大学"
高级操作符
SQL14 操作符混合运用
题目:现在运营想要找到gpa在3.5以上(不包括3.5)的山东大学用户 或 gpa在3.8以上(不包括3.8)的复旦大学同学进行用户调研,请你取出相应数据
select
device_id,gender,age,university,gpa
from user_profile
where (gpa > 3.5 and university = "山东大学") or (gpa > 3.8 and university = "复旦大学")
总结:由于AND操作符优先级高于or操作符,SQL在处理 OR操作符前,优先处理 AND操作符。该题目中括号可以不加,但为了更好的区分,看起来更加直观明了,本题使用括号加以区分。
高级查询
计算函数
SQL16 查找GPA最高的值
题目:运营想要知道复旦大学学生gpa最高值是多少,请你取出相应数据
select
max(gpa)
from user_profile
where university="复旦大学"
技巧:该题除了使用聚合函数MAX,还可以用ORDER BY进行降序排序,获取最大值,语句如下
select
gpa
from user_profile
where university = "复旦大学"
order by gpa desc
limit 1
分组查询
SQL18 分组计算练习题
题目:现在运营想要对每个学校不同性别的用户活跃情况和发帖数量进行分析,请分别计算出每个学校每种性别的用户数、30天内平均活跃天数和平均发帖数量。
select
gender,university,count(device_id) as user_num,avg(active_days_within_30) as avg_active_day,avg(question_cnt) as avg_question_cnt
from user_profile
group by gender,university
总结:平均值可加round取一位小数,看题目要求。
SQL19 分组过滤练习题
题目:现在运营想查看每个学校用户的平均发贴和回帖情况,寻找低活跃度学校进行重点运营,请取出平均发贴数低于5的学校或平均回帖数小于20的学校。
select
university,avg(question_cnt) as avg_question_cnt,avg(answer_cnt) as avg_answer_cnt
from user_profile
group by university
having avg(question_cnt) < 5 or avg(answer_cnt) <20
常见错误:select university,avg(question_cnt) as avg_question_cnt,avg(answer_cnt) as avg_answer_cnt from user_profile where avg(question_cnt) < 5 or avg(answer_cnt) < 20 group by university
where 不能跟聚合函数作为筛选条件,比如
where avg(××) <5,但是having 可以 ,having跟在分组 group by后面。
having的用法
having字句可以让我们筛选成组后的各种数据,where字句在聚合前先筛选记录,也就是说作用在group by和having字句前。
多表查询
子查询
SQL21 浙江大学用户题目回答情况
select
device_id,question_id,result
from question_practice_detail
where device_id = (select device_id from user_profile where university="浙江大学")
技巧:该题除了使用子查询,还可以使用表链接,语句如下
select
qpd.device_id as device_id,qpd.question_id as question_id,qpd.result as result
from question_practice_detail as qpd
inner join user_profile as up
on qpd.device_id = up.device_id and up.university = "浙江大学"
order by question_id