MySQL 计算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
−> );
Query OK, 0 rows affected (0.55 sec)
插入一些具有相同值的记录。对于我们的示例,我们为多个学生添加了相同的分数。插入记录的查询语句如下−
mysql> insert into RowWithSameValue values(100,'Carol',89);
Query OK, 1 row affected (0.21 sec)
mysql> insert into RowWithSameValue values(101,'Sam',89);
Query OK, 1 row affected (0.15 sec)
mysql> insert into RowWithSameValue values(102,'John',99);
Query OK, 1 row affected (0.12 sec)
mysql> insert into RowWithSameValue values(103,'Johnson',89);
Query OK, 1 row affected (0.15 sec)
现在,您可以显示我们上面插入的所有记录。显示所有记录的查询语句如下−
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)
阅读更多:MySQL 教程
极客教程