Mysql分組函數以及分組查詢

分組函數

功能:用作統計使用,又稱爲聚合函數或統計函數或組函數

分類:

sum 求和函數

select sum(屬性名)求出該屬性的數值和 

只能求數值的

avg 求平均值

select sum(屬性名)求出該屬性的平均值

只能求數值的

max 求最大值

select sum(屬性名)求出該屬性的最大值

可以求字符串的最大值

min 求最小值

select sum(屬性名)求出該屬性的最小值

可以求字符串的最小值

count 計算個數

select sum(屬性名)求出該屬性的個數

 

特點:

1.

sum、avg一般用於處理數值型

max、min、count可以處理任何類型

2.

sum、avg、count、max、min中null不參與運算

3.可以和distinct關鍵字搭配使用

在去除重複的列後再進行運算

如 select sum(distinct,salary)

4.count 函數

count(屬性) 求salary的行數

count(*) 求總行數(只要一行裏有某個屬性列不爲空,則總行數加1)

也可以用count(1)來統計行數,類似於在表裏加了一個屬性名爲1的列,然後統級它的個數

兩者的效率:

myisam存儲引擎下,count(*)效率高

innodb存儲引擎下,兩者差不多

5.和分組函數一同查詢的字段有限制

 

分組查詢

先看一下分組查詢的語法結構

select 分組函數
from table
where 篩選條件
group by 分組的列表
order by 子句

基本的分組查詢

例如查詢每個工種的最高工資

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

查詢每個部門的人數

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

添加篩選條件

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

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

 

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

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

添加複雜的篩選條件

查詢哪個部門的員工數>2

select count(*),department_id
from employees
group by department id
having count(*)>2

使用having語句,因爲where實在group前面實現的,此時還不知道每個部門的員工數,所以不能加在where裏。

查詢每個工種有獎金的員工的最高工資>12000的工種編號和最高工資

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

查詢領導編號>102的每個領導手下最低工資>5000的領導編號是哪個,以及最低工資

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

篩選總結:

篩選分爲分組前篩選和分組後篩選,分組前篩選用where,分組後篩選用having

 

按函數或表達式分組

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

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

按多個字段分組,多個字段用逗號隔開

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

select avg(salary),department_id,job_id
from employees
group by department_id,job_id;//只有department_id和job_id 一樣的時候才分組

添加排序

查詢每個部門每個工種的員工的平均工資,並按平均工資的高低顯示

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章