SQL语句——分组函数和分组查询
分組函數和分組查詢
- 一、分組函數
- 1、使用
- 2、注意
- (1)null
- (2)count(*)和count(具體字段)的區別
- (3)分組函數不能直接使用在where子句中
- (4)所有分組函數可以組合起來使用
- 二、分組查詢
- 1.注意
- 2.案例
一、分組函數
分組函數(多行處理函數)特點:輸入多行,最終輸出一行
分組函數在使用時必須先進行分組,然后才能使用;如果沒有對數據進行分組,整張表默認為一組。
(1)count 計數
(2)sum 求和
(3)avg 平均值
(4)max 最大值
(5)min 最小值
1、使用
(1)求最小/最大/平均/總和工資
select xxx(salay) from t_role; xxx:是上邊這些函數
2、注意
(1)null
分組函數自動忽略 Null ,不需要提前對 null 進行處理
(2)count(*)和count(具體字段)的區別
count(*):統計表當中的總行數(只要有一行數據,則count++)。因為每一行記錄不可能都為 null 。
count(具體字段):表示統計該字段下所有不為 null 的元素的總數。
(3)分組函數不能直接使用在where子句中
(1)找出比最低工資高的員工信息
select name,salay from t_role where salay>min(salay);:是錯誤的
(4)所有分組函數可以組合起來使用
二、分組查詢
1.注意
(1)關鍵字的組合使用順序
select
…
from
…
where
…
group by
…
order by
…
(2)執行順序,不能顛倒
from
where
group by
select
order by
(3)為什么分組函數不能直接使用在 where 后邊
為什么**select name,salay from t_role where salay>min(salay);**會報錯
因為分組函數在使用的時候必須先分組之后才能使用,where執行的時候,還沒有分組。
(4)為什么 select sum(salay) from t_role;,沒有分組卻可以使用呢?
因為 select 在 group by 之后才執行
2.案例
(1)找出每個工作崗位的工資和
select job,sum(salay) from emp group by job;
執行順序:先從 emp 表中查詢數據,再根據 job 字段進行分組,然后對每一組的數據進行 sum(salay)
重點結論:在一條 select 語句中,如果有 group by 語句的話, ** select** 后面只能跟參加分組的字段以及分組函數,其他一律不能跟。
(2)找出每個部門的最高薪資
select deptno,max(salay) from emp group by deptno;
(3)找出每個部門不同工作崗位的最高薪資
技巧:兩個字段連接成一個字段看(兩個字段聯合起來分組)
select deptno,job,max(salay) from emp group by deptno,job;
(4)找出每個部門的最高薪資,要求顯示最高薪資大于3000的
使用 having 可以對分完組之后的數據進一步過濾。 having 不能單獨使用, having 不能代替 where , having 必須和 group by 聯合使用
select deptno,max(salay) from emp where salay>3000 group by deptno
也可以:select deptno,max(salay) from emp group by deptno having max(salay)>3000;
優化策略:優先選擇 where,where 完成不了再選擇 having。
總結
以上是生活随笔為你收集整理的SQL语句——分组函数和分组查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DDNS技术总结
- 下一篇: 【详细】Redis学习教程全