iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 19
3
Modern Web

淺談資料庫&ASP.net&C# 入門系列 第 19

[iT鐵人賽Day19]SQL語法-常用的聚合函數 COUNT()、AVG() 、MAX() 、MIN()、 SUM()

聚合函數

可以執行所選取的欄位值的筆數、平均、統計等,以便資料分析。

常用的聚合函數如下:

https://ithelp.ithome.com.tw/upload/images/20190920/20119925OB7XNxJE7O.png

COUNT()

SQL語法可使用COUNT()函數來計算指定欄位的數量。

()內可以使用「 * 」來統計資料表所有的資料有幾筆數量,或放入指定的欄位名稱來統計該欄位不是null的資料數量。

SQL範例:

Customers資料表

https://ithelp.ithome.com.tw/upload/images/20190920/20119925zfk75Os0Cg.png

查詢Customers有幾筆資料:

select count( * ) as 總共有幾筆資料 from Customers

顯示結果有5筆,就算lg那一列有null,使用 * 同列其中一欄位有資料就會算是有資料的。

https://ithelp.ithome.com.tw/upload/images/20190920/20119925P5Z4uTS2Yg.png

不過要查詢tel有幾筆資料數量:

select count(tel) as 總共有幾筆資料 from Customers

顯示結果只會有4筆,因為lg那一列為null值。

https://ithelp.ithome.com.tw/upload/images/20190920/201199250HwiSOjaNZ.png

而現在要查詢地址在日本的客戶有幾個:

select count( * ) as 總共有幾筆資料 from Customers where address='Japan'

因為只有一筆地址是在Japan,所以結果會是一筆。

https://ithelp.ithome.com.tw/upload/images/20190920/20119925MoGjThrKsW.png

AVG()

AVG()可以計算指定欄位資料的平均值,()內欄位名稱可計算該欄位平均值。

SQL範例:

Products資料表
https://ithelp.ithome.com.tw/upload/images/20190920/20119925QyZOXw2px1.png

計算Products 的價格平均

select avg(price) as 價格平均 from Products

顯示結果:
https://ithelp.ithome.com.tw/upload/images/20190920/20119925elWqxKqLqV.png

計算有「糖」字串的價格平均值及數量:

select avg(price) as 價格平均,count(name)as 總量 from Products where name like '%糖%'

顯示結果:
https://ithelp.ithome.com.tw/upload/images/20190920/20119925uzJ2hfCRJM.png

MAX()

MAX()可以計算()內欄位資料的最大值。

SQL範例:

一樣Products資料表,要算出Products資料表內價格最大值是幾元。

select max(price) as 最大值 from Products

顯示結果:
https://ithelp.ithome.com.tw/upload/images/20190920/20119925VF13npKidG.png

但假如要有其他欄位顯示明顯的可以知道哪一筆是最大值,可以這樣用。

select top 1 * from [dbo].[Products] order by price desc

https://ithelp.ithome.com.tw/upload/images/20190920/201199250WsrbMhnX4.png

MIN()

MIN()可以計算()內欄位資料的最小值。

SQL範例:

算出Products資料表內價格最小值是幾元。

select min(price) as 最小值 from Products

https://ithelp.ithome.com.tw/upload/images/20190920/20119925QWMiPRoXlI.png

MAX跟MIN也可以下where條件。

select min(price) as 最小值 from Products where name like '%糖%'

不過剛好有糖的最小值剛好也是100所以結果是一樣的。

SUM()

SUM()可以計算欄位資料的總和。

SQL範例:

計算Products資料表價錢的總和與平均:

select sum(price) as 總和 , avg(price) as 平均 from Products

結果如下:

https://ithelp.ithome.com.tw/upload/images/20190920/20119925Sbtm2Zy5Ho.png

搜尋只有糖字串的總和與平均:

select sum(price) as 總和 , avg(price) as 平均 from Products where name like '%糖%'

結果如下:

https://ithelp.ithome.com.tw/upload/images/20190920/20119925tzhR3nQ8cx.png


上一篇
[iT鐵人賽Day18]SQL語法-排序Order by
下一篇
[iT鐵人賽Day20]SQL語法-GROUP BY 資料分組
系列文
淺談資料庫&ASP.net&C# 入門36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言