參考:
想要弄懂GROUP BY看這一篇就夠了
數(shù)據(jù)庫:group by 的使用
聚合函數(shù)
1.MAX:返回某列的最大值
2.MIN(column) 返回某列的最高值
3.COUNT(column) 返回某列的總行數(shù)
4.COUNT(*) 返回表的總行數(shù) (包含null)
5.SUM(column) 返回某列的相加總和
6.AVG(column) 返回某列的平均值
GROUP BY
語句根據(jù)一個(gè)或多個(gè)列對(duì)結(jié)果集進(jìn)行分組
常用語句:
單個(gè)字段分組
select grade from student group by grade 查出學(xué)生等級(jí)的種類(按照等級(jí)劃分帽衙,去除重復(fù)的)按照多個(gè)字段分組
select name , sum(salary) from student group by name , grade 按照名字和等級(jí)劃分,查看相同名字下的工資總和
注意:這里有一點(diǎn)需要說明一下袭灯,多個(gè)字段進(jìn)行分組時(shí)铁坎,需要將name和grade看成一個(gè)整體腰涧,只要是name和grade相同的可以分成一組;如果只是name相同,grade不同就不是一組榴捡。group_concat函數(shù)是將歸類后的名字以逗號(hào)連接成字符串
select job ,group_concat(ename) from emp group by job;求每個(gè)部門所有工資總和匹中。
select deptno,sum(sal) from emp group by deptno;查詢每個(gè)部門工資大于1500的的人數(shù)
select deptno,count(*) from emp where sal >1500 group by deptno;
1.工資>1500 2.按部門分組 3.統(tǒng)計(jì)人數(shù)
HAVING
HAVING用于分組后的再次篩選,只能用于分組夏漱。(注意:分組后)
求工資總和大于9000的部門,并按照工資總和排序。
select deptno,sum(sal) total from emp group by deptno having sum(sal) >9000
order by sum(sal) asc;
having和where區(qū)別:
1.having是分組后顶捷,where是分組前
2.where不用使用聚合函數(shù)挂绰,having可以使用聚合函數(shù)。
3.where在分組之前就會(huì)進(jìn)行篩選服赎,過濾掉的數(shù)據(jù)不會(huì)進(jìn)入分組葵蒂。
執(zhí)行順序
關(guān)鍵字的書寫順序如下:
1.select
2.from
3.where
4.group by
5.having
6.order by
7. limit
關(guān)鍵字的執(zhí)行順序如下:
1.from //行過濾
2.where
3.group by
4.having
5.select //列過濾
6.order by//排序
7.limit//附加