Oracle學習筆記<5>

組函數(多值函數)數據庫

數據庫中函數的分類:
1)單值函數 Single Rows Functions
特色:n條數據參與函數處理,最終獲得n條結果。
2)多值函數(組函數) Multiple Rows Functions
特色:n條數據參與函數處理,獲得的結果可能小於n。


1.常見的組函數
avg 計算平均值
max 計算最大值
min 計算最小值
sum 計算代數和
count 計算某個字段非空字段值的總數量函數

 

2.組函數語法
select 函數名(字段名)
from 表名
where 條件
[group by 要分組的字段]
[having 分組以後的查詢條件];spa

group by若是不出現,則視爲將表中的全部數據分爲一個大組。
最終的組函數運算只有一個結果。排序


關鍵字:
1)group by 用來指定分組的依據,
例如:group by 字段A
在分組時就會把全部字段A的值相等的
數據分爲一組。
2)having
作限定性查詢的。
功能相似於where。ip

位置
1)group by關鍵字出如今where子句的後面。
2)having 出如今group by後面。
六大關鍵字書寫順序:
select .. 5
from .. 1
where .. 2
group by .. 3
having .. 4
order by.. 6字符串

 

注意:
1)出如今select後面的字段,
要麼是組函數,要麼是出如今group by後面的字段。
即分組的依據字段。
2)where和having的區別
where發生在分組以前,
定義的是有關單值篩選的條件。
在where後面不容許出現組函數。
having發生在分組以後,
定義的是有關小組的篩選條件。
在having後面不容許出現單值條件判斷。域名

 

 

練習:
1.查看各個部門的最高工資
select max(salary)
from s_emp
group by dept_id;
2.查看各個部門的員工數
count函數 計算某個字段非空字段值的數量

count(*) 把全部字段的字段值數量都計算出來,
取最大的爲查詢結果。
count(1)it

3.查詢各個部門各個職稱的平均薪水和最大薪水,而且平均薪水大於2000的部門id;
根據多個字段進行分組:
group by 字段1,字段2...
分組時將全部出如今group by後面的字段值都相等的數據
分爲一組。
select avg(salary),max(salary),dept_id
from s_emp
group by dept_id,title
having avg(salary) > 1000;io


4.查詢title中不包含vp字符串的每一個職位的平均薪水和總薪水,並對平均薪水進行降序排列,而且每一個職位的總薪水大於5000?
select avg(salary),sum(salary)
from s_emp
where title not like '%vp%'
group by title
having sum(salary) > 5000
order by avg(salary) desc;ast

做業:
1)查詢全部員工的平均工資,最高工資最低工資,工資總和,還有有多少個員工?
select avg(salary),max(salary),min(salary),
sum(salary),count(*)
from s_emp;
2)查詢每一個部門的平均工資?對平均工資降序排序.平均工資大於1400.
select avg(salary)
from s_emp
group by dept_id
having avg(salary) > 1400
order by avg(salary) desc;
3)查看各個部門的最高工資
select dept_id,max(salary)
from s_emp
group by dept_id;
4)查看各個部門的員工數
select count(*)
from s_emp
group by dept_id;
5)查詢各個部門各個職稱的平均薪水和最大薪水,
而且平均薪水大於2000的部門id。
select avg(salary),max(salary),dept_id
from s_emp
group by dept_id,title
having avg(salary) > 2000;
6)查詢title中不包含vp字符串的每一個職位的平
均薪水,並對平均薪水進行降序排列,而且每一個職位
的總薪水大於5000。
select avg(salary)
from s_emp
where title not like '%vp%'
group by title
having sum(salary) > 5000
order by avg(salary) desc;

8)查看每一個區域部門數?
區域-部門:1對多
select count(*)
from s_dept
group by region_id;

查詢每一個部門的員工數?
select count(*)
from s_emp
group by dept_id;
9)查詢南美地區的部門數?
區域名字 = 南美
select count(*)
from s_dept d,s_region r
where d.region_id = r.id
and r.name = 'South America';
10)查詢南美地區工資大於1400的員工的信息?
三表查詢
select e.id,e.last_name,e.salary
from s_emp e,s_dept d,s_region r
where e.dept_id = d.id
and d.region_id = r.id
and r.name = 'South America'
and e.salary > 1400;

方式二:子查詢(嵌套查詢)
select id,last_name,salary
from s_emp
where dept_id in(select d.id
from s_dept d,s_region r
where d.region_id = r.id
and r.name = 'South America');

SQL:查詢全部工做在南美區域的部門id? select d.id from s_dept d,s_region r where d.region_id = r.id and r.name = 'South America';

相關文章
相關標籤/搜索