SQL——統計檢索函數

分組:group by 字段名  將此字段值相同的分到一組一塊顯示

select * from 表 
where ...
gruop by 字段名1[,字段名2];
--gruop by 所帶的字段爲多個時,把多個看成一組,都相同爲一組。

注:加group by後select 後的結果列必須是組的共同代表
錯誤示例:

select 
sname "姓名",--加這一行會報錯,因爲結果是每組一行,但每組卻並沒有統一的的sname,所以出錯
sclass "班級",
count(*) "人數",
count(sage) "年齡數",
avg(sage) "平均年齡",
min(sage) "最小年齡",
max(sage) "最大年齡",
sum(sage) "總年齡"
from student
group by sclass

count :計數

count(*):統計表中記錄數
count(字段名):統計字段值不爲空的記錄條數
沒有gruop by :整個table
有gruop by : 分組內

sum:求和

sum(字段名):對每組內,個條記錄相應字段的值求和

avg:均值

avg(字段名):組內的平均值=sum/count 字段名爲number型
注:空值不參與運算

min、max:組內最小\大值

min(字段名)、max(字段名)
注:字段爲文本按ASCII碼排大小,null值不參與計算

drop table student;

create table student
(
sno char(5),
sname varchar2(20),
sage number(2),
sclass char(5)
); 

insert into student values('10001','Tom',29,'97001');
insert into student values('10002','Lili',20,'97004');
insert into student values('10003','Jerry',22,'97001');
insert into student values('10004','Anti',21,'97002');
insert into student values('10005','John',null,'97002');
commit;

select * from student;

select 
sclass "班級",
count(*) "人數",
count(sage) "年齡數",
avg(sage) "平均年齡",
min(sage) "最小年齡",
max(sage) "最大年齡",
sum(sage) "總年齡"
from student
group by sclass;

--having語句:只要某一組的數據
select 
sname "姓名",--會報錯,因爲結果是每組一行,但每組卻並沒有統一的的sname,所以出錯
sclass "班級",
count(*) "人數",
count(sage) "年齡數",
avg(sage) "平均年齡",
min(sage) "最小年齡",
max(sage) "最大年齡",
sum(sage) "總年齡"
from student
group by sclass
havin sclass='97001';


 

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