在 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)
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP