SQLite COUNT()函數
SQLite COUNT()
函數用於檢索表達式或給定列的行數。
語法
SELECT COUNT(aggregate_expression)
FROM tables
[WHERE conditions];
在GROUP BY
子句中使用COUNT()
函數時的語法:
SELECT expression1, expression2, ... expression_n
COUNT(aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;
示例1:
假設有一個名爲student
的表,具有以下數據:
從student
表中檢索AGE
大於22
的學生人數:
SELECT COUNT(*) AS "Number of students"
FROM STUDENT
WHERE AGE > 22;
執行上面查詢代碼,得到以下結果 -
sqlite> SELECT COUNT(*) AS "Number of students"
...> FROM STUDENT
...> WHERE AGE > 22;
8
sqlite>
示例2:
計算AGE
大於22
歲的學生人數,並按學生名字分組。
SELECT NAME, COUNT(*) AS "Number Of Students"
FROM STUDENT
WHERE AGE > 22
GROUP BY NAME;
執行上面代碼,得到以下結果 -
sqlite> SELECT NAME, COUNT(*) AS "Number Of Students"
...> FROM STUDENT
...> WHERE AGE > 22
...> GROUP BY NAME;
Avgsu|1
Linsu|2
Maxsu|2
Minsu|2
Sqlsu|1
sqlite>
示例3:
計算每個地址的學生總人數,按學生地址(Address
)分組。
SELECT ADDRESS, COUNT(*) AS "Number Of Students"
FROM STUDENT
GROUP BY ADDRESS;
執行上面代碼,得到以下結果 -
sqlite> SELECT ADDRESS, COUNT(*) AS "Number Of Students"
...> FROM STUDENT
...> GROUP BY ADDRESS;
Beijing|1
Guangzhou|2
Haikou|2
Shanghai|1
Shengzhen|2
Shenzhen|1
sqlite>