數據庫分組

數據庫分組

distinct 去除重複記錄

查詢公司中有哪些工作崗位job

select distinct job from emp;

查詢公司中工作崗位job的數量

select count(distinct job) from emp;

去除部門編號deptno和工作崗位job重複記錄

說明:只有在出現多條deptno和job纔會清楚的

select distinct deptne,job from emp;

group by分組

找出每個職位的最高薪水sal

寫法一

select max(sal) from emp group by job; 

寫法二

注意:在有group by的DQL詢句中,select語句後面只能跟 聚合函數 + 參與分組的字段

select job,max(sal) from emp group by job;

計算每個工作崗位的最高薪水,並且按照由高到低排序

select job,max(sal) as maxSal from emp group by job order by maxSal desc;

計算每個部門deptne的平均薪水

select deptne,avg(sal) from emp group by deptne;

計算不同部門deptne不同崗位job的最高薪水

select deptne,job,max(sal) from emp group by deptne,job;

計算除了manager之外的每個工作崗位的最高薪水

select job,max(sal) as maxSal from emp where job <> 'manager' group by job;

where和having區別

  • where和having都是爲了完成數據的過濾,它們後面都是添加條件;
  • where是在 group by之前完成過濾;
  • having是在group by之後完成過濾;

having過濾

作用:如果想對分組的數據進行過濾,需要使用having子句

找出每個工作崗位job的平均薪水sal,要求顯示平均薪水大於2000的:

錯誤寫法
原因:where後面不能直接使用聚合函數。

select job,avg(sal) as avgsal from emp where avg(sal)>2000 group by job;

正確寫法

select job,avg(sal) from emp group by job having avg(sal) > 2000;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章