在单个MySQL查询中实现多个COUNT()
为此,请使用CASE语句。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> LastName varchar(100) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Smith'); mysql> insert into DemoTable values('Brown'); mysql> insert into DemoTable values('Brown'); mysql> insert into DemoTable values('Smith'); mysql> insert into DemoTable values('Taylor'); mysql> insert into DemoTable values('Taylor'); mysql> insert into DemoTable values('Miller'); mysql> insert into DemoTable values('Miller'); mysql> insert into DemoTable values('Miller');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
输出结果
这将产生以下输出-
+----------+ | LastName | +----------+ | Smith | | Brown | | Brown | | Smith | | Taylor | | Taylor | | Miller | | Miller | | Miller | +----------+ 9 rows in set (0.00 sec)
以下是COUNT()
在一个查询中实现多种方法的查询-
mysql> select COUNT(CASE WHEN LastName='Smith' THEN 1 END) AS TotalFrequency, -> COUNT(CASE WHEN LastName='Brown' THEN 1 END) AS TotalFrequency, -> COUNT(CASE WHEN LastName='Taylor' THEN 1 END) AS TotalFrequency, -> COUNT(CASE WHEN LastName='Miller' THEN 1 END) AS TotalFrequency -> from DemoTable;
输出结果
这将产生以下输出-
+----------------+----------------+----------------+----------------+ | TotalFrequency | TotalFrequency | TotalFrequency | TotalFrequency | +----------------+----------------+----------------+----------------+ | 2 | 2 | 2 | 3 | +----------------+----------------+----------------+----------------+ 1 row in set (0.00 sec)