在 MySQL 中计算特定列中值出现的次数?

mysqlmysqli database

您可以将聚合函数 count() 与 group by 结合使用。语法如下。

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)

相关文章