SQL教程——group by语法

本教程中所使用的数据库的建表语句都在“SQL教程——索引”这篇文章中,点击链接直达:索引&建表语句

摘要:本文主要SQL语句中where的语法和使用

 

group by

 

语法:

    select 分组函数,列(要求出现在group by的后面)

    form 表

    【where 筛选条件】

    group by 分组的列表

    【order by字句】 

特点:

1、分组查询中的筛选条件分为两类

 数据源位置关键字
分组前筛选 原始表group by字句前面where
分组后筛选分组后的结果集group by字句后面having

注意:如果用分组函数做条件进行筛选,一定是放在having子句中。

 

2、group by字句支持单个字段分组,也支持多个字段分组,还支持表达式和函数分组(用的较少)

         

3、也可以添加排序,放在最后

 

 

思考:查询每个部门的平均工资

select avg(salary) 平均工资, department_id 部门编号 from employees group by department_id;

 

 #question1:查询每个工种的最高工资:

select max(salary), job_id from employees group by job_id;

 

#question2:查询每个位置上的部门个数

select count(*) 部门数量, location_id 位置编号 from departments group by location_id;

#或者是

select count(department_id ) 部门数量, location_id 位置编号 from departments group by location_id;

 

#question3:查询邮箱中包含a字符的,每个部门的平均工资        #分组前的筛选

select avg(salary), department_id, email from employees where email like '%a%' group by department_id;

 

#question4:查询每个领导手下有奖金的员工的最高工资。

select max(salary), manager_id from employees where commission_pct is not null group by manager_id;

 

#question5:查询员工个数>2的部门            having的用法        #分组后的筛选

select  department_id from employees group by department_id having count(*) > 2;

#或者更直观的

select  department_id from employees group by department_id having count(*) > 2;

 

#question6:查询每个工种有奖金的员工的最高工资>12000的工种编号和最高工资。

select job_id, max(salary) from employees where commission_pct is not null group by job_id having max(salary) > 12000; 

 

#question7:查询领导编号>102的每个领导手下员工的最低工资>5000的领导编号是哪个,以及其最低工资

select manager_id, min(salary) from employees where manager_id > 102 group by manager_id having min(salary) > 5000;

 

#question8:按员工姓名的长度分组,查询每一组的员工的个数,筛选员工个数>5的有哪些

select count(*), length(last_name) from employees group by length(last_name) having count(*) > 5;

#别名的使用:要注意的是where后面不能放别名,group by和having可以,但是这种做法不常用,因为Oracle不支持where、group by、having后面放别名。

select count(*) c, length(last_name) len_name from employees group by len_name having c > 5;

 

#按照多个字段分组

#question9:查询每个部门每个工种的员工的平均工资

select avg(salary), department_id, job_id from employees group by department_id, job_id;

 

#添加排序

#question10:查询每个部门每个工种的员工的平均工资,并且按平均工资高低排序显示。

select avg(salary), department_id, job_id from employees group by department_id, job_id order by avg(salary),department_id; 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

请保持优秀。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值