为此,您可以将COUNT()与CASE STATEMENT一起使用。让我们首先创建一个表-
create table DemoTable ( Score int );
使用插入命令在表中插入一些记录-
insert into DemoTable values(40); insert into DemoTable values(48); insert into DemoTable values(59); insert into DemoTable values(33); insert into DemoTable values(38); insert into DemoTable values(89); insert into DemoTable values(35);
使用select语句显示表中的所有记录-
select *from DemoTable;
这将产生以下输出-
+-------+ | Score | +-------+ | 40 | | 48 | | 59 | | 33 | | 38 | | 89 | | 35 | +-------+ 7 rows in set (0.00 sec)
以下是对大于或小于特定值的值进行计数并在单独的列中显示计数的查询-
select count( case when Score > 45 then 1 end) as CountOfValueGreaterThan45, count( case when Score <= 45 then 1 end) as CountOfValueLessThanOrEqualTo45 from DemoTable;
这将产生以下输出-
+---------------------------+---------------------------------+ | CountOfValueGreaterThan45 | CountOfValueLessThanOrEqualTo45 | +---------------------------+---------------------------------+ | 3 | 4 | +---------------------------+---------------------------------+ 1 row in set (0.00 sec)