如何在 MySQL 中对 varchar 列求和并显示计数?
为此,请使用 GROUP BY 和 COUNT(*)。我们首先创建一个表 -
mysql> create table DemoTable ( EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, EmployeeGender varchar(40) ); Query OK, 0 rows affected (0.48 sec)
使用 insert 命令插入表中的一些记录 -
mysql> insert into DemoTable(EmployeeGender) values('MALE'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(EmployeeGender) values('FEMALE'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(EmployeeGender) values('FEMALE'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable(EmployeeGender) values('FEMALE'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(EmployeeGender) values('MALE'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable(EmployeeGender) values('MALE'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(EmployeeGender) values('MALE'); Query OK, 1 row affected (0.07 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将生成以下输出 -
+------------+----------------+ | EmployeeId | EmployeeGender | +------------+----------------+ | 1 | MALE | | 2 | FEMALE | | 3 | FEMALE | | 4 | FEMALE | | 5 | MALE | | 6 | MALE | | 7 | MALE | +------------+----------------+ 7 rows in set (0.00 sec)
以下是用来计算 varchar 列的查询。这将计算 MALE 和 FEMALE 列的值,并显示计数 -
mysql> select EmployeeGender,count(*) from DemoTable group by EmployeeGender;
这将生成以下输出 -
+----------------+----------+ | EmployeeGender | count(*) | +----------------+----------+ | MALE | 4 | | FEMALE | 3 | +----------------+----------+ 2 rows in set (0.00 sec)
广告