前言: 之前用过MySQL数据库很多次,但是有一些命令使用比较少,容易忘记,比如去重distinct,is not null, in, 降序排列desc, 精度函数round(), 平均值函数avg, 计数函数count(), 分组函数group by等等,用牛客网的题目简单回顾一下。
牛客网编程地址:https://www.nowcoder.com/exam/oj?tab=SQL%E7%AF%87&topicId=199
# 去重
select distinct university from user_profile;
# 去除非空
select device_id, gender, age, university from user_profile where age is not null;
# in 的用法
select device_id, gender, age, university, gpa from user_profile where university in ('北京大学' , '复旦大学' , '山东大学');
# desc
select device_id , gpa, age from user_profile order by gpa desc, age desc;
# round函数 和 avg 函数 和 count函数 和group by
select
gender, university,
count(id) as user_num,
round(avg(active_days_within_30), 1) as avg_active_day,
round(avg(question_cnt), 1) as avg_question_cnt
from user_profile
group by gender, university;
1.SQL38.查找后降序排列
select device_id , gpa, age from user_profile order by gpa desc, age desc;
2.SQL17计算男生人数以及平均GPA
select
count(gender) as male_num,
avg(gpa) as avg_gpa
from user_profile where gender = 'male';
3.SQL18.分组计算
select
gender, university,
count(id) as user_num,
round(avg(active_days_within_30), 1) as avg_active_day,
round(avg(question_cnt), 1) as avg_question_cnt
from user_profile
group by gender, university;
4.SQL19 分组过滤练习题
注意如果是聚合函数作为筛选条件,不能用where字句,应该用havaing.
select
university,
round(avg(question_cnt), 3) as avg_question_cnt,
round(avg(answer_cnt), 3) as avg_answer_cnt
from user_profile
group by university
having avg_question_cnt < 5 or avg_answer_cnt < 20
5.SQL20 分组排序练习题
对分组后的数据排序,直接使用order by 即可。
select
university,
avg(question_cnt) as avg_question_cnt
from user_profile
group by university
order by avg_question_cnt