如何在varchar列中求和并在MySQL中显示计数?

为此,将GROUP BY与COUNT(*)一起使用。让我们首先创建一个表-

create table DemoTable
(
   EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   EmployeeGender varchar(40)
);

使用插入命令在表中插入一些记录-

insert into DemoTable(EmployeeGender) values('MALE');
insert into DemoTable(EmployeeGender) values('FEMALE');
insert into DemoTable(EmployeeGender) values('FEMALE');
insert into DemoTable(EmployeeGender) values('FEMALE');
insert into DemoTable(EmployeeGender) values('MALE');
insert into DemoTable(EmployeeGender) values('MALE');
insert into DemoTable(EmployeeGender) values('MALE');

使用select语句显示表中的所有记录-

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列值求和,并显示计数-

select EmployeeGender,count(*) from DemoTable
   group by EmployeeGender;

这将产生以下输出-

+----------------+----------+
| EmployeeGender | count(*) |
+----------------+----------+
| MALE           |        4 |
| FEMALE         |        3 |
+----------------+----------+
2 rows in set (0.00 sec)
猜你喜欢