为此,您可以将聚合函数SUM()与条件一起使用。让我们首先创建一个表-
create table DemoTable -> ( -> Status varchar(20) -> );
使用插入命令在表中插入一些记录-
insert into DemoTable values('active'); insert into DemoTable values('active'); insert into DemoTable values('active'); insert into DemoTable values('active');
使用select语句显示表中的所有记录-
select *from DemoTable;
这将产生以下输出-
+--------+ | Status | +--------+ | active | | active | | active | | active | +--------+ 4 rows in set (0.00 sec)
这是查询以显示零值的行-
select -> sum(Status='active') as 'CountOfActive', -> sum(Status='inactive') as 'CountOfInActive' -> from DemoTable;
这将产生以下输出。在这里,对于非活动状态,表中没有记录,因此0可见-
+---------------+-----------------+ | CountOfActive | CountOfInActive | +---------------+-----------------+ | 4 | 0 | +---------------+-----------------+ 1 row in set (0.30 sec)