如何计算 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)
广告