group?by用法詳解
一. ?概述
group_by的意思是根據(jù)by對數(shù)據(jù)按照哪個字段進(jìn)行分組,或者是哪幾個字段進(jìn)行分組。
二. ?語法
select ? 字段 ? ?from ? 表名 ? where ? ?條件 ? ? group ? by? ? ? ?字段
或者
select ? 字段 ? ?from ? 表名 ? group ?by ? ?字段 ? ?having ? ?過濾條件
注意:對于過濾條件,可以先用where,再用group ?by或者是先用group ?by,再用having
三. ?案例
1 ?創(chuàng)建表格并插入數(shù)據(jù)
說明:在plsql ?developer上創(chuàng)建表格并插入數(shù)據(jù),以便下面進(jìn)行簡單字段分組以及多個字段分組,同時還結(jié)合聚合函數(shù)進(jìn)行運(yùn)算。
創(chuàng)建student表
? ? ? create table student
(id ?int not null ,
name varchar2(30),
grade varchar2(30),
salary ?varchar2(30)
)
在student表中插入數(shù)據(jù)
insert into student values(1,'zhangsan','A',1500);
insert into student values(2,'lisi','B',3000);
insert into student values(1,'zhangsan','A',1500);
insert into student values(4,'qianwu','A',3500);
insert into student values(3,'zhaoliu','C',2000);
insert into student values(1,'huyifei','D',2500);
數(shù)據(jù)插入到student表中的結(jié)果
2 ?單個字段分組
① ?select ? grade ? from ? student ? ? ? ? ? ? ? 查出所有學(xué)生等級(包括重復(fù)的等級)
② ?select ?grade ?from ?student ? group ? by ? grade ? ? ? 查出學(xué)生等級的種類(按照等級劃分,去除重復(fù)的)
3 ?多個字段分組
select ?name , sum(salary) ? ?from ? student ? ?group ?by ? name , grade ? ? ?按照名字和等級劃分,查看相同名字下的工資總和
注意:這里有一點(diǎn)需要說明一下,多個字段進(jìn)行分組時,需要將name和grade看成一個整體,只要是name和grade相同的可以分成一組;如果只是name相同,grade不同就不是一組。
4 ?配合聚合函數(shù)一起使用
常用的聚合函數(shù):count() , sum() , avg() , max() , min()
count():計(jì)數(shù)
select ?name , count(*) ?from ?student ? group ?by ?name ? ? ? ? ? 查看表中相同人名的個數(shù)
得出的如下結(jié)果
sum():求和
select ?name , sum(salary) ? from ? student ? group ?by ? name ? ? ?查看表中人員的工資和(同姓的工資相加)
得出的如下結(jié)果
avg():平均數(shù)
select ?name , avg(salary) ? from ?student ? group ?by ?name ?, grade ? ? ??查看表中人員的工資平均數(shù)(同姓工資平均數(shù))
得出的如下結(jié)果
max():最大值
select ? grade , max(salary) ? from ? student ? group ?by ? grade ? ? ? ? ??查看按等級劃分人員工資最大值
得出的如下結(jié)果
min():最小值
select ? grade , min(salary) ? from ? student ? group ?by ? grade ? ? ? ?查看按等級劃分人員工資最小值
得出的如下結(jié)果
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。