在 MySQL 中使用相同 ID 但记录不同的值(“是”,“否”)的计数选择
为此,你可以将 SUM() 与 CASE 语句结合使用。让我们首先创建一个 -
mysql> create table DemoTable1430 -> ( -> EmployeeId int, -> isMarried ENUM('YES','NO') -> ); Query OK, 0 rows affected (0.60 sec)
使用 insert 在表中插入一些记录 -
mysql> insert into DemoTable1430 values(1001,'Yes'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1430 values(1001,'No'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1430 values(1001,'Yes'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable1430 values(1001,'Yes'); Query OK, 1 row affected (0.16 sec)
使用 select 从表中显示所有记录 -
mysql> select * from DemoTable1430;
这将产生以下输出 -
+------------+-----------+ | EmployeeId | isMarried | +------------+-----------+ | 1001 | YES | | 1001 | NO | | 1001 | YES | | 1001 | YES | +------------+-----------+ 4 rows in set (0.00 sec)
以下是对值(“是”,“否”)数量进行选择的查询 -
mysql> select EmployeeId,sum(isMarried='Yes') as NumberOfMarried, -> sum(isMarried='No') as NumberOfUnMarried -> from DemoTable1430 -> group by EmployeeId;
这将产生以下输出 -
+------------+-----------------+-------------------+ | EmployeeId | NumberOfMarried | NumberOfUnMarried | +------------+-----------------+-------------------+ | 1001 | 3 | 1 | +------------+-----------------+-------------------+ 1 row in set (0.00 sec)
广告