要获取不同的值并计算它们,可以使用GROUP BY子句。
语法如下
select yourColumnName,count(*) as anyAliasName from yourTableName group by yourColumnName;
为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table GroupByAndCountDemo -> ( -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientName varchar(100) -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into GroupByAndCountDemo(ClientName) values('John'); mysql> insert into GroupByAndCountDemo(ClientName) values('Carol'); mysql> insert into GroupByAndCountDemo(ClientName) values('Sam'); mysql> insert into GroupByAndCountDemo(ClientName) values('Sam'); mysql> insert into GroupByAndCountDemo(ClientName) values('John'); mysql> insert into GroupByAndCountDemo(ClientName) values('John'); mysql> insert into GroupByAndCountDemo(ClientName) values('John'); mysql> insert into GroupByAndCountDemo(ClientName) values('Sam'); mysql> insert into GroupByAndCountDemo(ClientName) values('Sam'); mysql> insert into GroupByAndCountDemo(ClientName) values('Sam'); mysql> insert into GroupByAndCountDemo(ClientName) values('John'); mysql> insert into GroupByAndCountDemo(ClientName) values('John'); mysql> insert into GroupByAndCountDemo(ClientName) values('John'); mysql> insert into GroupByAndCountDemo(ClientName) values('David'); mysql> insert into GroupByAndCountDemo(ClientName) values('Maxwell'); mysql> insert into GroupByAndCountDemo(ClientName) values('Maxwell');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from GroupByAndCountDemo;
输出如下
+----------+------------+ | ClientId | ClientName | +----------+------------+ | 1 | John | | 2 | Carol | | 3 | Sam | | 4 | Sam | | 5 | John | | 6 | John | | 7 | John | | 8 | Sam | | 9 | Sam | | 10 | Sam | | 11 | John | | 12 | John | | 13 | John | | 14 | David | | 15 | Maxwell | | 16 | Maxwell | +----------+------------+ 16 rows in set (0.00 sec)
现在,让我们获取不同的值并使用以下查询对它们进行计数
mysql> select ClientName,count(*) as TotalCount from GroupByAndCountDemo group by ClientName;
以下是输出
+------------+------------+ | ClientName | TotalCount | +------------+------------+ | John | 7 | | Carol | 1 | | Sam | 5 | | David | 1 | | Maxwell | 2 | +------------+------------+ 5 rows in set (0.00 sec)