在 MySQL 中使用 group by 对两个字段进行计数?

mysqlmysqli database

要实现对两个字段进行 GROUP BY 并计数,让我们创建一个表。以下是创建表的查询 −

mysql> create table GroupByTwoFieldsDemo
   −> (
   −> Id int,
   −> Name varchar(200)
   −> );
Query OK, 0 rows affected (0.53 sec)

Let us insert some records in the table −

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)

相关文章