常见的SQL命令-参考牛客网

前言: 之前用过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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值