SQL 計數()
COUNT() 函數傳回符合指定條件的行數。
SQL COUNT(column_name) 語法
COUNT(column_name) 函數傳回指定列的值的數目(NULL 不計入):
SELECT COUNT(column_name) FROM table_name;
SQL COUNT(*) 語法
COUNT(*) 函數傳回表中的記錄數:
SELECT COUNT(*) FROM table_name;
SQL COUNT(DISTINCT column_name) 語法
COUNT(DISTINCT column_name) 函數傳回指定列的不同值的數目:
SELECT COUNT(DISTINCT column_name) FROM table_name;
註解:COUNT(DISTINCT) 適用於ORACLE 和Microsoft SQL Server,但無法用於Microsoft Access。
示範資料庫
在本教學中,我們將使用 php 樣本資料庫。
下面是選自"access_log" 表的資料:
+-----+---------+------- +------------+
| aid | site_id | count | date |
+-----+---------+---- ---+------------+
| 1 | 1 | 45 | 2016-05-10 1 2001 |
| 3 | 1 | 230 | 2016-05-14 |
| 4 | 5 | 5 | 205 | 2016-05-14 |
| 6 | 4 | 13 | 2016-05-15 |
| 7 | 3 | 220 | 2016-05-15 |
| 8 | 5 | 545 | 2016-05-16 |
| 9 | 3 | 201 | 2016-05-17 |
+-----+---------+-------+----------- -+
| aid | site_id | count | date |
+-----+---------+---- ---+------------+
| 1 | 1 | 45 | 2016-05-10 1 2001 |
| 3 | 1 | 230 | 2016-05-14 |
| 4 | 5 | 5 | 205 | 2016-05-14 |
| 6 | 4 | 13 | 2016-05-15 |
| 7 | 3 | 220 | 2016-05-15 |
| 8 | 5 | 545 | 2016-05-16 |
| 9 | 3 | 201 | 2016-05-17 |
+-----+---------+-------+----------- -+
#下面的SQL 語句計算"access_log" 表中"site_id"=3 的總存取量:
實例SELECT COUNT(count) AS nums FROM access_log
WHERE site_id=3;SQL COUNT(*) 實例
#下面的SQL 語句計算"access_log" 表中總記錄數:
實例
#SELECT COUNT(*) AS nums FROM access_log;
執行上述SQL 輸出結果如下:
##SQL COUNT(DISTINCT column_name ) 實例下面的SQL 語句計算"access_log" 表中不同site_id 的記錄數:
實例SELECT COUNT(DISTINCT site_id) AS nums FROM access_log ;執行上述SQL 輸出結果如下: