group by ,having, 聚合函式的使用
前言: 在此之前對資料庫中的group by 和having以及聚合函式一起使用的規則很模糊,今天特意總結了三者之間的使用規則,希望也能幫助到各位。
1: count() max() min() avg() sum() 聚合函式
作用:count() 統計總記錄數,max() 取最大值,min()取最小值,avg()取平均值,sum() 總和
例子:select count(sid) from grade where cid=3; 查詢參加科目編號為3考試的同學總數
select max(scgrade) from grade where cid=1; 查詢參加科目編號為1考試的所有同學中的最高分數
select min(scgrade) from grade where cid=1; 查詢參加科目編號為1考試的所有同學中的最低分數
select sum(scgrade) from grade where sid=5; 統計參加科目編號為5考試的所有同學分數的總和
select avg(scgrade) from grade where cid=1; 查詢參加科目編號為1考試的所有同學中的平均分
講解: count()括號中的引數適於所有的欄位,而後面的四種聚合函式主要是針對數字型別的欄位。
2:group by 分組
作用:group by 是select語句的從句,用來指定查詢分組條件,主要用來對查詢的結果進行分組,相同組合的分組條件在 結果集中只顯示一行記錄
例子: select sid ,count(cid) from grade group by sid; 根據分數表(grade)查詢出每一個學生(sid 學生編號)共參加了幾 科的考試(cid 科目編號);
講解:group by 後面跟的欄位必需是在select 出現的欄位 ,且select 後的欄位只能為group by 欄位和聚合函式。
3: having 判斷
作用:having子句的作用就是為每一個組指定條件,像where指定條件一樣,也就是說,可以根據你指定的 條件來選擇行。
例子: select sids from (select sid as sids from group where scgrade<60) group by sids having count(sids)>=2; 查詢超過兩科沒及格的學生id
講解:having必須處在group by子句之後 。
補允:where 和having的區別。
where:where 子句在聚合前先篩選記錄.也就是說作用在group by 子句和having子句前.
having:having子句在聚合後對組記錄進行篩選
---------------------
作者:christine_ruan
來源:CSDN
原文:https://blog.csdn.net/christine_ruan/article/details/7569782
版權宣告:本文為博主原創文章,轉載請附上博文連結!