计算MySQL中有多少行具有相同的值?

要使用功能COUNT(*)和GROUP BY计算多少行具有相同的值。语法如下-

SELECT yourColumName1, count(*) as anyVariableName from yourTableName GROUP BY yourColumName1;

为了理解上述语法,让我们首先创建一个表。创建表的查询如下-

mysql> create table RowWithSameValue
   −> (
   −> StudentId int,
   −> StudentName varchar(100),
   −> StudentMarks int
   −> );

插入一些具有相同值的记录。在此,我们为示例中的多个学生添加了相同的标记。插入记录的查询如下-

mysql> insert into RowWithSameValue values(100,'Carol',89);

mysql> insert into RowWithSameValue values(101,'Sam',89);

mysql> insert into RowWithSameValue values(102,'John',99);

mysql> insert into RowWithSameValue values(103,'Johnson',89);

现在,您可以显示我们在上面插入的所有记录。显示所有记录的查询如下-

mysql> select *from RowWithSameValue;

以下是输出-

+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
|       100 | Carol       |           89 |
|       101 | Sam         |           89 |
|       102 | John        |           99 |
|       103 | Johnson     |           89 |
+-----------+-------------+--------------+
4 rows in set (0.00 sec)

实施我们开头讨论的语法以对具有相同值的行进行计数-

mysql> SELECT StudentMarks, count(*) as SameValue from RowWithSameValue GROUP BY StudentMarks;

以下是显示多个值的计数的输出-

+--------------+-----------+
| StudentMarks | SameValue |
+--------------+-----------+
|           89 |         3 |
|           99 |         1 |
+--------------+-----------+
2 rows in set (0.00 sec)