在 MySQL 中使用 group by 对两个字段进行分组并统计吗?
要对两个字段和计数实现 GROUP BY,我们创建一个表。以下是用于创建表的查询 -
mysql> create table GroupByTwoFieldsDemo −> ( −> Id int, −> Name varchar(200) −> ); Query OK, 0 rows affected (0.53 sec)
让我们在表中插入一些记录 -
mysql> insert into GroupByTwoFieldsDemo values(1,'John'); Query OK, 1 row affected (0.15 sec) mysql> insert into GroupByTwoFieldsDemo values(10,'Johnson'); Query OK, 1 row affected (0.16 sec) mysql> insert into GroupByTwoFieldsDemo values(9,'Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into GroupByTwoFieldsDemo values(6,'Sam'); Query OK, 1 row affected (0.16 sec) mysql> insert into GroupByTwoFieldsDemo values(5,'David'); Query OK, 1 row affected (0.20 sec) mysql> insert into GroupByTwoFieldsDemo values(10,'Johnson'); Query OK, 1 row affected (0.15 sec) mysql> insert into GroupByTwoFieldsDemo values(6,'Sam'); Query OK, 1 row affected (0.17 sec)
在 select 语句的帮助下显示表中的所有记录。查询如下 -
mysql> select *from GroupByTwoFieldsDemo;
以下是输出 -
+------+---------+ | Id | Name | +------+---------+ | 1 | John | | 10 | Johnson | | 9 | Carol | | 6 | Sam | | 5 | David | | 10 | Johnson | | 6 | Sam | +------+---------+ 7 rows in set (0.00 sec)
以下是分组为两列并进行计数的语法 -
select yourColumnName1,yourColumnName2,....N,count(yourColumnName1) from GroupByTwoFieldsDemo group by yourColumnName1 desc,yourColumName2;
应用上述语法对两列进行分组,并显示重复值的计数 -
mysql> select Id,Name,count(Id) from GroupByTwoFieldsDemo group by id desc,Name;
以下是输出 -
+------+---------+-----------+ | Id | Name | count(Id) | +------+---------+-----------+ | 10 | Johnson | 2 | | 9 | Carol | 1 | | 6 | Sam | 2 | | 5 | David | 1 | | 1 | John | 1 | +------+---------+-----------+ 5 rows in set, 1 warning (0.00 sec)
广告