牛客-SQL篇-非技术快速入门篇
💗 未来的游戏开发程序媛,现在的努力学习菜鸡
💦本专栏用来记录我最近的数据库学习,分为知识点和刷题记录两个部分
🈶本篇是我牛客网的刷题记录
牛客-SQL篇-非技术快速入门篇(1-20)
我的答案
SQL1 查询所有列
select * from user_profile;
SQL2 查询多列
select device_id,gender,age,university from user_profile;
SQL3 查询结果去重
select distinct university from user_profile;
SQL4 查询结果限制返回行数
select device_id from user_profile limit 2;
SQL5 将查询后的列重新命名
select device_id from user_profile limit 2;
alter table user_profile change device_id user_infos_example int ;
SQL6 查找学校是北大的学生信息
select device_id,university from user_profile where university = '北京大学';
SQL7 查找年龄大于24岁的用户信息
select device_id,gender,age,university from user_profile where age > 24;
SQL8 查找某个年龄段的用户信息
select device_id,gender,age from user_profile where age between 20 and 23;
SQL9 查找除复旦大学的用户信息
select device_id,gender,age,university from user_profile where university != '复旦大学';
SQL10 用where过滤空值练习
select device_id,gender,age,university from user_profile where age is not null;
SQL11 高级操作符练习(1)
select device_id,gender,age,university,gpa
from user_profile
where gpa > 3.5 and gender = 'male';
SQL12 高级操作符练习(2)
select device_id,gender,age,university,gpa
from user_profile
where university = '北京大学' or gpa >3.7;
SQL13 Where in 和Not in
select device_id,gender,age,university,gpa
from user_profile
where university in ('北京大学','复旦大学','山东大学');
SQL14 操作符混合运用
select device_id,gender,age,university,gpa
from user_profile
where (gpa>3.5 and university='山东大学')or(gpa>3.8 and university = '复旦大学');
SQL15 查看学校名称中含北京的用户
select device_id,age,university
from user_profile
where university like '北京%';
SQL16 查找GPA最高值
select max(gpa)
from user_profile
where university = '复旦大学';
SQL17 计算男生人数以及平均GPA
select count(gender),avg(gpa)
from user_profile
where gender ='male'
group by gender;
SQL18 分组计算练习题
select gender,university,count(gender) ,avg(active_days_within_30),avg(question_cnt)
from user_profile
group by gender,university;
SQL19 分组过滤练习题
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;
我的错误答案
错误原因:没按大学分组,并且在使用聚合函数的同时,用where进行条件查询。
涉及的知识点:
where和having的区别
- where是分组之前进行过滤,不满足条件的不进行分组;where不能对聚合函数进行判断。
- having是分组之后对结果进行过滤;having能对聚合函数进行判断。
SQL20 分组排序练习题
select university,avg(question_cnt) as avg_question_cnt
from user_profile
group by university
order by avg_question_cnt;
我的错误答案
错误原因:order by 后面加了分组之前的名字question_cnt;
涉及的知识点:
DQL语句 | 编写顺序 | 执行顺序 |
---|---|---|
select 字段列表 | 1 | 4 |
from 表名列表 | 2 | 1 |
where 条件列表 | 3 | 2 |
group by 分组字段列表 | 4 | 3 |
order by 排序字段列表 | 5 | 5 |
limit 分页参数 | 6 | 6 |