本次將討論數據庫查詢中的排序,分組和聚合函數的使用
排序
查詢結果排序分為升序和降序
<code>select 列名1 from 表名 where 條件 order by 列名1 desc;/<code>
- 列名1結果降序排列(從高到低)
- 當然where子句根據條件可加可不加
<code>select 列名1 from 表名 where 條件 order by 列名1 asc;/<code>
- 列名1結果升序排列(從低到高)
如果多個字段結果參與排序如何?
<code>select 列名1,列名2 from 表名 where 條件 order by 列名1 asc,列名2 desc;/<code>
- 該句表示列名1按照升序排列,列名2按照降序排列
- 如果需要還可以繼續加排序字段
分組
分組查詢是根據指定字段按照一定規則進行分組,分組以後數據會聚合,配合使用聚合函數,比如班級課程表按照課程分組,按照性別分組等
<code>select 列名1,列名2...... from 表名 group by 表名.字段1;/<code>
如果對分組查詢使用篩選條件的話,不能使用where,需要使用having關鍵字
<code>select 列名1,列名2...... from 表名 group by 表名.字段1 having 條件子句;/<code>
聚合函數
聚合函數同時可以對多行數據進行操作,返回一個結果。聚合函數通常與分組操作結合使用,但是也不一定配合分組使用
<code>select count(列名) from 表名;/<code>
- count() 統計數量
<code>select sum(列名) from 表名;/<code>
- sum() 求和
<code>select max(列名) from 表名;/<code>
- max() 求最大值
<code>select min(列名) from 表名;/<code>
- min() 求最小值
<code>select avg(列名) from 表名;/<code>
- avg() 求平均值
<code>select round(列名) from 表名;/<code>
- round() 數值四捨五入
閱讀更多 出水菱角 的文章