1. 程式人生 > 實用技巧 >MYSQL 第五課 分組函式

MYSQL 第五課 分組函式

二 分組函式

/*功能:用作統計使用,又稱為聚合函式或統計函式或組函式

分類:
sum 求和、avg 平均值、max 最大值 、min 最小值 、count 計算個數

特點:
1、sum、avg一般用於處理數值型
max、min、count可以處理任何型別
2、以上分組函式都忽略null值

3、可以和distinct搭配實現去重的運算

4、count函式的單獨介紹
一般使用count(*)用作統計行數

5、和分組函式一同查詢的欄位要求是group by後的欄位

*/

#1、簡單 的使用

SELECT SUM(salary) FROM employees;
SELECT AVG(salary) FROM
employees; SELECT MIN(salary) FROM employees; SELECT MAX(salary) FROM employees; SELECT COUNT(salary) FROM employees;

SELECT SUM(salary) 和,AVG(salary) 平均,MAX(salary) 最高,MIN(salary) 最低,COUNT(salary) 個數
FROM employees;

SELECT SUM(salary) 和,ROUND(AVG(salary),2) 平均,MAX(salary) 最高,MIN(salary) 最低,COUNT
(salary) 個數 FROM employees;

#2、引數支援哪些型別

SELECT SUM(last_name) ,AVG(last_name) FROM employees;
SELECT SUM(hiredate) ,AVG(hiredate) FROM employees;

SELECT MAX(last_name),MIN(last_name) FROM employees;

SELECT MAX(hiredate),MIN(hiredate) FROM employees;

SELECT COUNT(commission_pct) FROM employees;
SELECT COUNT(last_name) FROM employees;

#3、是否忽略null

SELECT SUM(commission_pct) ,AVG(commission_pct),SUM(commission_pct)/35,SUM(commission_pct)/107 FROM employees;

SELECT MAX(commission_pct) ,MIN(commission_pct) FROM employees;

SELECT COUNT(commission_pct) FROM employees;
SELECT commission_pct FROM employees;


#4、和distinct搭配

SELECT SUM(DISTINCT salary),SUM(salary) FROM employees;

SELECT COUNT(DISTINCT salary),COUNT(salary) FROM employees;

#5、count函式的詳細介紹

SELECT COUNT(salary) FROM employees;


SELECT COUNT(*) FROM employees;

SELECT COUNT(1) FROM employees;

效率:
MYISAM儲存引擎下 ,COUNT(*)的效率高
INNODB儲存引擎下,COUNT(*)和COUNT(1)的效率差不多,比COUNT(欄位)要高一些


#6、和分組函式一同查詢的欄位有限制

SELECT AVG(salary),employee_id FROM employees;

例題

#1.查詢公司員工工資的最大值,最小值,平均值,總和

SELECT MAX(salary) 最大值,MIN(salary) 最小值,AVG(salary) 平均值,SUM(salary) 和
FROM employees;


#2.查詢員工表中的最大入職時間和最小入職時間的相差天數 (DIFFRENCE)

SELECT MAX(hiredate) 最大,MIN(hiredate) 最小,(MAX(hiredate)-MIN(hiredate))/1000/3600/24 DIFFRENCE
FROM employees;

SELECT DATEDIFF(MAX(hiredate),MIN(hiredate)) DIFFRENCE
FROM employees;

SELECT DATEDIFF('1995-2-7','1995-2-6');

#3.查詢部門編號為90的員工個數

SELECT COUNT(*) FROM employees WHERE department_id = 90;