九、MySql数据库--分组查询(四)

一、分组查询

GROUP BY 子句
		
		
		1.where语句中不能使用聚合函数。
		2.单行函数与聚合函数不允许混合使用,分组查询时除外。
				如果没有分组查询,SELECT 列表中不允许出现字段(单行函数)与分组函数混用的情况。   		
		2.分组查询时,可使用where限定查询条件,可使用Order by 子句指定排序方式  
		3.分组查询时,SELECT列表中的字段或者order by后面的字段必须出现在group by子句中,或者被聚合函数包含。
		
			
		
		  

		例子:
			 select empno, sal from emp; //合法  
			 select avg(sal) from emp; //合法 
			 select empno, initcap(ename), avg(sal) from emp; //非法 
			 不允许在  WHERE 子句中使用分组函数。 
			 select deptno, avg(sal)  from emp  where avg(sal) > 2000;  group by deptno;  


HAVING 子句
		 
		 having子句,必须跟着groupby才能用
		 有having不一定有groupby ,有groupby必须有having
	
	
					 select deptno, job, avg(sal) 
					 from emp
					  where hiredate >= to_date('1981-05-01','yyyy-mm-dd') 
					 group by deptno,job 
					 having avg(sal) > 1200
					 order by deptno,job;  

 

二、练习



1.分组统计各部门下工资>500 的员工的平均工资
  Select avg(sal) from emp where sal>500 group by deptno ;

select   avg(e.sal)    from emp  e where e.sal>500 group by  e.deptno
2. 统计各部门下平均工资大于500 的部门      
 select deptno,avg(sal) from emp group by deptno having avg(sal)>500 ;  
 select e.deptno ,avg(e.sal) from  emp  e group by e.deptno  having avg(e.sal)>500
3.算出部门30 中得到最多奖金的员工奖金       
Select max(comm) from emp where deptno = 30 ;  
 select max(nvl(e.comm,0)) from emp  e where e.deptno=30
4.算出部门30 中得到最多奖金的员工姓名       
 select ename from emp where comm = (select max(comm) from emp where       deptno=30); 
 

select e.ename from emp e  where e.comm=( select max(nvl(e.comm,0)) from emp  e where e.deptno=30)
5. 算出每个职位的员工数和最低工资       
Select  job,min(sal),count(*) from emp group by job;
 select count(*),min(e.sal) from emp e group by e.job
6.算出每个部门,,每个职位的平均工资和平均奖金(平均值包括没有奖金) ,如果平均奖金大于300,显示“奖 金不错”,如果平均奖金100 到300,显示“奖金一般”,如果平均奖金小于100,显示“基本没有奖金”, 按部门编号降序,平均工资降序排列       
Select  avg(sal),avg(nvl(comm,0)), case  when  avg(nvl(comm,0))>300  then  ‘奖金不错’     when avg(nvl(comm,0))<100 and avg(nvl(comm,0))>300 then  ‘奖金不错’  end  奖金状况       from emp group by job order by job desc,avg(sal) desc;  
 

select avg(nvl(e.sal, 0)),
       avg(nvl(e.comm, 0)),
       case
         when avg(nvl(e.sal, 0)) > 300 then
          '奖金不错'
         when avg(nvl(e.sal, 0)) > 300 then
          '奖金一般'
         when avg(nvl(e.sal, 0)) > 300 then
          '基本没有奖金'
       end 奖金
  from emp e
 group by e.deptno, e.job

7.列出员工表中每个部门的员工数,和部门no       
Select count(*),deptno from emp group by deptno; 

 select count(*),e.deptno from  emp e group by e.deptno
8.得到工资大于自己部门平均工资的员工信息  
select * from emp e1,(select deptno,avg(sal) as avgsal from emp group by deptno) e2     where e1.deptno=e2.deptno and e1.sal > e2.avgsal;  
 
9.分组统计每个部门下,每种职位的平均奖金(也要算没奖金的人)和总工资(包括奖金)  
select deptno,job,avg(nvl(comm,0)),sum(sal+nvl(comm,0)) from emp group by deptno,job;



发布了94 篇原创文章 · 获赞 0 · 访问量 642

猜你喜欢

转载自blog.csdn.net/weixin_45602227/article/details/104148184