MySQL-分組查詢

分組查詢

語法

select 分組函數,列(要求出現在group by的後面)
from 表
【where 篩選條件】
group by 分組的列表
【order by 子句】

查詢列表必須是分組函數和group by後出現的字段

案例

簡單分組查詢

1、查詢每個工種的最高工資

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

2、查詢每個位置上的部門個數

select count(*),location_id
from departments
group by location_id;

添加分組條件

1、查詢郵箱中包含a字符的,每個部門的平均工資

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

2、查詢有獎金的每個領導手下員工的最高工資

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

添加複雜的篩選條件

1、查詢哪個部門的員工個數大於2

  • 查詢每個部門的員工個數
  • 查詢哪個部門的員工個數大於2
select count(*),department_id
from employees
group by department_id
having count(*)>2;

2、查詢每個工種有獎金的員工的最高工資大於12000的工種編號和最高工資

  • 查詢每個工種有獎金的員工的最高工資
  • 對結果進行篩選,最高工資大於12000
select max(salary),job_id
from employees
where commission_pct is not null
group by job_id
having max(salary)>12000;

3、查詢領導編號>102的每個領導手下的最低工資大於5000的領導編號,以及最低工資

  • 查詢每個領導手下的最低工資
  • 篩選出領導編號大於102的
  • 篩選最低工資大於5000的
select min(salary),manager_id
from employees
where manager_id>102
group by manager_id
having min(salary)>5000;

按表達式或函數分組

1、按員工姓名的長度分組,查詢每一組的員工個數,篩選員工個數大於5的有哪些

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

按多個字段分組

1、查詢每個部門每個工種的員工的平均工資

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

添加排序

1、查詢每個部門每個工種的員工的平均工資

select avg(salary),department_id,job_id
from employees
where department_id is not null
group by department_id,job_id
having avg(salary)>10000
order by avg(salary) desc;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章