計算特定列中的值在 MySQL 中出現的次數?
可以對 group by 使用聚合函式 count()。語法如下。
select yourColumnName,count(*) as anyVariableName from yourtableName group by yourColumnName;
為了理解上述語法,讓我們建立一個表格。建立表格的查詢如下。
mysql> create table CountSameValue -> ( -> Id int, -> Name varchar(100), -> Marks int -> ); Query OK, 0 rows affected (0.70 sec)
使用 insert 命令在表格中插入記錄。查詢如下。
mysql> insert into CountSameValue values(1,'Sam',67); Query OK, 1 row affected (0.17 sec) mysql> insert into CountSameValue values(2,'Mike',87); Query OK, 1 row affected (0.19 sec) mysql> insert into CountSameValue values(3,'Carol',67); Query OK, 1 row affected (0.24 sec) mysql> insert into CountSameValue values(4,'Bob',87); Query OK, 1 row affected (0.18 sec) mysql> insert into CountSameValue values(5,'John',71); Query OK, 1 row affected (0.17 sec) mysql> insert into CountSameValue values(6,'Adam',66); Query OK, 1 row affected (0.18 sec) mysql> insert into CountSameValue values(7,'David',71); Query OK, 1 row affected (0.20 sec) mysql> insert into CountSameValue values(8,'Maria',67); Query OK, 1 row affected (0.16 sec)
使用 select 語句顯示錶格中的所有記錄。查詢如下。
mysql> select *from CountSameValue;
以下是輸出。
+------+-------+-------+ | Id | Name | Marks | +------+-------+-------+ | 1 | Sam | 67 | | 2 | Mike | 87 | | 3 | Carol | 67 | | 4 | Bob | 87 | | 5 | John | 71 | | 6 | Adam | 66 | | 7 | David | 71 | | 8 | Maria | 67 | +------+-------+-------+ 8 rows in set (0.00 sec)
以下是統計列中值(分數)出現次數的查詢。查詢如下。
mysql> select Marks,count(*) as Total from CountSameValue group by Marks;
以下是輸出。
+-------+-------+ | Marks | Total | +-------+-------+ | 67 | 3 | | 87 | 2 | | 71 | 2 | | 66 | 1 | +-------+-------+ 4 rows in set (0.00 sec)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP