在单个 MySQL 查询中获取两个表字段的计数?
为此,你可以将 CASE 语句与 SUM() 一起使用。这里,我们将查找一列员工性别值中男性和女性记录的计数。让我们首先创建一个表 -
mysql> create table DemoTable ( EmployeeGender ENUM('Male','Female') ); Query OK, 0 rows affected (0.52 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values('Male'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('Female'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Male'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Female'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable values('Male'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable values('Female'); Query OK, 1 row affected (0.08 sec)
使用 select 语句从表中显示所有记录 -
mysql> select *from DemoTable;
这将生成以下输出 -
+----------------+ | EmployeeGender | +----------------+ | Male | | Female | | Male | | Female | | Male | | Female | +----------------+ 6 rows in set (0.00 sec)
以下是获取一个查询中两个表字段计数的查询 -
mysql> select sum(case when EmployeeGender='Male' then 1 else 0 end) as Total_Number_Of_Male_Employee, sum(case when EmployeeGender='Female' then 1 else 0 end) as Total_Number_Of_Female_Employee from DemoTable;
这将生成以下输出 -
+-------------------------------+---------------------------------+ | Total_Number_Of_Male_Employee | Total_Number_Of_Female_Employee | +-------------------------------+---------------------------------+ | 3 | 3 | +-------------------------------+---------------------------------+ 1 row in set (0.00 sec
广告