SQL語句複習【專題二】

SQL語句複習【專題二】sql

單行函數(日期、數學、字符串、通用函數、轉換函數)
多行函數。分組函數。多行數據計算一個結果。
一共5個。sum(),avg(),max(),min(),count()
分組函數   分類
只能處理數值型的數據  sum 、avg
max,min,count ,任何類型均可以處理。函數

--求全部的員工的最高工資,平均工資,工資總和,最小工資,員工的人數。
select max(sal) 最高工資 ,avg(sal) 平均工資 ,sum(sal) 工資總和 ,min(sal) 最小工資, count(*) spa

--統計部門編號是 10 的員工的總數
select count(*) from emp where deptno=10
select count(*) from emp where deptno=20
select count(*) from emp where deptno=30排序

分組查詢--group by
--統計排除10部門,其餘部門的總人數,工資的總和,工資的平均值,工資的最大值,工資的最小值,使用工資的總和排序 desc
select deptno,sum(sal),avg(sal),max(sal),min(sal),count(*)
from emp
where deptno<>10
group by deptno
order by sum(sal) desc
--使用別名排序
select deptno,sum(sal) 工資總和,avg(sal),max(sal),min(sal),count(*)
from emp
where deptno<>10
group by deptno
order by 工資總和 desc字符串

sql 書寫順序有嚴格的要求,必須遵照【sql 執行的順序:from--->where--->group by---select --->order by
---統計每一個部門的總人數,工資的總和,工資的平均值,工資的最大值,工資的最小值,使用工資的總和排序,只顯示工資的平均值 >= 2000
select deptno, count(*),sum(sal),avg(sal),max(sal),min(sal)
from emp
where avg(sal) >= 2000---where 後面跟的行過濾條件,不能跟分組的函數,不能進行分組以後的條件的過濾。  不能夠
group by deptno
order by sum(sal)
正確寫法
select deptno, count(*),sum(sal),avg(sal),max(sal),min(sal)
from emp
--where avg(sal) >= 2000---where 後面跟的行過濾條件,不能跟分組的函數,不能進行分組以後的條件的過濾。
group by deptno
order by sum(sal)
數學

having:是進行分組過濾的條件的關鍵字。後面能夠跟 where 使用的任何的內容。
sql 注意書寫順序【sql 執行的順序:from--->where--->group by--->having--->select --->order by】
--統計部門人數,平均工資,排除10部門,和平均工資> 1000的部門
select deptno, count(*), avg(sal)
from emp
where deptno<>10
group by deptno
having avg(sal) > 1000
--使用別名
select deptno as 部門編號 , count(*) 部門人數 , avg(sal) 平均工資
from emp
where deptno<>10
group by deptno
having avg(sal) > 1000---只能使用avg(sal) 不能使用別名。別名的生效是在select 執行以後纔有效的。而having實在 select以前執行的。
order by 平均工資 desc--order by 最後排序,能夠使用select 中的別名。select

多字段分組
--平均工資大於1200的部門和工做的組合
select deptno, job,avg(sal)
from emp
group by deptno, job
having avg(sal)>1200統計

--統計部門人數小於4的部門的平均工資 和 人數
select deptno, count(*), avg(sal)
from emp
group by deptno
having count(*) < 4數據

--統計各部門最高工資,排除最高工資小於3000的部門
select deptno, max(sal)
from emp
group by deptno
having max(sal) >= 3000查詢

相關文章
相關標籤/搜索