统计 MySQL 列中每一行的相同值?
若要统计每一行的相同值,请结合使用 COUNT(*) 和 GROUP BY 子句。我们首先创建一个表 -
mysql> create table DemoTable1818 ( Id int, Name varchar(20) ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1818 values(10,'Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1818 values(11,'Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1818 values(11,'Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1818 values(12,'Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1818 values(10,'Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1818 values(10,'Chris'); Query OK, 1 row affected (0.00 sec)
使用 select 语句从表中显示所有记录 -
mysql> select * from DemoTable1818;
这会生成以下输出 -
+------+-------+ | Id | Name | +------+-------+ | 10 | Chris | | 11 | Chris | | 11 | Chris | | 12 | Chris | | 10 | Chris | | 10 | Chris | +------+-------+ 6 rows in set (0.00 sec)
以下是用于统计列中每行相同值并显示输出的查询 -
mysql> select Id,count(*) as TotalPerId from DemoTable1818 group by Id;
这会生成以下输出 -
+------+------------+ | Id | TotalPerId | +------+------------+ | 10 | 3 | | 11 | 2 | | 12 | 1 | +------+------------+ 3 rows in set (0.00 sec)
广告