SQL (函數) SUM、 AVG、COUNT
針對資料庫中某些資料型態是數值類型做運算動作,如果想將欄位做一些運算,就可使用 SUM、 AVG、COUN 函數來找出資料。
SELECT 函數(欄位) FROM 資料表
例如 :
SELECT SUM(UnitPrice) FROM Products ;
ProductID |
ProductName |
QuantityPerUnit |
UnitPrice |
UnitsInStock |
1 |
Chai |
10 boxes x 20 bags |
18.00 |
39 |
2 |
Chang |
24 - 12 oz bottles |
19.00 |
17 |
3 |
Aniseed Syrup |
12 - 550 ml bottles |
10.00 |
13 |
4 |
Queso Manchego La Pastora |
10 - 500 g pkgs. |
38.00 |
86 |
5 |
Konbu |
2 kg box |
6.00 |
24 |
6 |
Tofu |
40 - 100 g pkgs. |
23.25 |
35 |
7 |
Teatime Chocolate Biscuits |
10 boxes x 12 pieces |
9.20 |
25 |
8 |
Carnarvon Tigers |
16 kg pkg. |
62.50 |
42 |
9 |
Grandma's Boysenberry Spread |
12 - 8 oz jars |
25.00 |
120 |
10 |
Sir Rodney's Marmalade |
30 gift boxes |
81.00 |
40 |
結果:
SELECT count(ProductID) FROM Products ;
ProductID |
ProductName |
QuantityPerUnit |
UnitPrice |
UnitsInStock |
1 |
Chai |
10 boxes x 20 bags |
18.00 |
39 |
2 |
Chang |
24 - 12 oz bottles |
19.00 |
17 |
3 |
Aniseed Syrup |
12 - 550 ml bottles |
10.00 |
13 |
4 |
Queso Manchego La Pastora |
10 - 500 g pkgs. |
38.00 |
86 |
5 |
Konbu |
2 kg box |
6.00 |
24 |
6 |
Tofu |
40 - 100 g pkgs. |
23.25 |
35 |
7 |
Teatime Chocolate Biscuits |
10 boxes x 12 pieces |
9.20 |
25 |
8 |
Carnarvon Tigers |
16 kg pkg. |
62.50 |
42 |
9 |
Grandma's Boysenberry Spread |
12 - 8 oz jars |
25.00 |
120 |
10 |
Sir Rodney's Marmalade |
30 gift boxes |
81.00 |
40 |
結果:
SELECT AVG(UnitPrice) FROM Products ;
ProductID |
ProductName |
QuantityPerUnit |
UnitPrice |
UnitsInStock |
1 |
Chai |
10 boxes x 20 bags |
18.00 |
39 |
2 |
Chang |
24 - 12 oz bottles |
19.00 |
17 |
3 |
Aniseed Syrup |
12 - 550 ml bottles |
10.00 |
13 |
4 |
Queso Manchego La Pastora |
10 - 500 g pkgs. |
38.00 |
86 |
5 |
Konbu |
2 kg box |
6.00 |
24 |
6 |
Tofu |
40 - 100 g pkgs. |
23.00 |
35 |
7 |
Teatime Chocolate Biscuits |
10 boxes x 12 pieces |
9.00 |
25 |
8 |
Carnarvon Tigers |
16 kg pkg. |
62.00 |
42 |
9 |
Grandma's Boysenberry Spread |
12 - 8 oz jars |
25.00 |
120 |
10 |
Sir Rodney's Marmalade |
30 gift boxes |
81.00 |
40 |
結果:
額外補充,在 GROUP BY 語句可搭配 WHERE、 HAVING 查詢此欄位的運算資料 SUM (加總)、 AVG(平均)、COUNT (計算數量)