选择具有相同ID但MySQL中对应记录不同的值的计数(是,否)?
为此,您可以SUM()
与CASE语句一起使用。让我们首先创建一个-
mysql> create table DemoTable1430 -> ( -> EmployeeId int, -> isMarried ENUM('YES','NO') -> );
使用insert在表中插入一些记录-
mysql> insert into DemoTable1430 values(1001,'Yes'); mysql> insert into DemoTable1430 values(1001,'No'); mysql> insert into DemoTable1430 values(1001,'Yes'); mysql> insert into DemoTable1430 values(1001,'Yes');
使用选择显示表中的所有记录-
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)