MySQL全面瓦解10:分組查詢和聚合函式

翁智華發表於2020-11-16

概述

相信我們經常會遇到這樣的場景:想要了解雙十一天貓購買化妝品的人員中平均消費額度是多少(這可能有利於對商品價格區間的定位);或者不同年齡段的化妝品消費佔比是多少(這可能有助於對商品備貨量的預估)。

這個時候就要用到分組查詢,分組查詢的目的是為了把資料分成多個邏輯組(購買化妝品的人員是一個組,不同年齡段購買化妝品的人員也是組),並對每個組進行聚合計算的過程:。

分組查詢的語法格式如下:

1 select cname, group_fun,... from tname [where condition]
2 group by group_expression [having group_condition]; 

說明一下:

1、group_fun 代表聚合函式,是指對分組的資料進行聚合計算的函式。

2、group_expression 代表分組表示式,允許多個,多個之間使用逗號隔開。

3、group_condition 分組之後,再對分組後的資料進行條件過濾的過程。

4、分組語法中,select後面出現的欄位 要麼是group by後面的欄位,要麼是聚合函式的列,其他型別會報異常,我們下面的內容中會詳細說明。 

說分組之前,先來看看聚合函式,聚合函式是分組查詢語法格式中重要的一部分。我們經常需要彙總資料而不用把它們實際檢索出來,所以MySQL供了專門的函式。使用這些函式,可用於計算我們需要的資料,以便分析和生成報表。

聚合函式

聚合函式有以下幾種。 

函式 說明
AVG() 返回指定欄位的平均值
COUNT() 返回查詢結果行數
MAX() 返回指定欄位的最大值 
MIN() 返回指定欄位的最小值
SUM() 返回指定欄位的求和值

AVG()函式

AVG()通過對錶中行數計數並計算特定列值之和,求得該列的平均值。 AVG()可用來返回所有列的平均值,也可以用來返回特定列或行的平均值。

下面示例返回使用者表中使用者的平均年齡:

 1 mysql> select * from user2;
 2 +----+--------+------+----------+-----+
 3 | id | name   | age  | address  | sex |
 4 +----+--------+------+----------+-----+
 5 |  1 | brand  |   21 | fuzhou   |   1 |
 6 |  2 | helen  |   20 | quanzhou |   0 |
 7 |  3 | sol    |   21 | xiamen   |   0 |
 8 |  4 | weng   |   33 | guizhou  |   1 |
 9 |  5 | selina |   25 | NULL     |   0 |
10 |  6 | anny   |   23 | shanghai |   0 |
11 |  7 | annd   |   24 | shanghai |   1 |
12 |  8 | sunny  | NULL | guizhou  |   0 |
13 +----+--------+------+----------+-----+
14 8 rows in set
15 
16 mysql> select avg(age) from user2;
17 +----------+
18 | avg(age) |
19 +----------+
20 | 23.8571  |
21 +----------+
22 1 row in set 

注意點:

1、AVG()只能用來確定特定數值列的平均值 。
2、AVG()函式忽略列值為NULL的行,所以上圖中age值累加之後是除以7,而不是除以8。 

 

COUNT()函式

COUNT()函式進行計數。 可以用COUNT()確定表中符合條件的行的數目。

count 有 count(*)、count(具體欄位)、count(常量) 三種方式來體現 下面 演示了count(*) 和 count(cname)的用法。

 1 mysql> select * from user2;
 2 +----+--------+------+----------+-----+
 3 | id | name   | age  | address  | sex |
 4 +----+--------+------+----------+-----+
 5 |  1 | brand  |   21 | fuzhou   |   1 |
 6 |  2 | helen  |   20 | quanzhou |   0 |
 7 |  3 | sol    |   21 | xiamen   |   0 |
 8 |  4 | weng   |   33 | guizhou  |   1 |
 9 |  5 | selina |   25 | NULL     |   0 |
10 |  6 | anny   |   23 | shanghai |   0 |
11 |  7 | annd   |   24 | shanghai |   1 |
12 |  8 | sunny  | NULL | guizhou  |   0 |
13 +----+--------+------+----------+-----+
14 8 rows in set
15 
16 mysql> select count(*) from user2 where sex=0;
17 +----------+
18 | count(*) |
19 +----------+
20 |        5 |
21 +----------+
22 1 row in set
23 
24 mysql> select count(age) from user2 where sex=0;
25 +------------+
26 | count(age) |
27 +------------+
28 |          4 |
29 +------------+
30 1 row in set 

可以看到,都是取出女生的使用者數量,count(*) 比 count(age) 多一個,那是因為age中包含null值。

所以:如果指定列名,則指定列的值為空的行被COUNT()函式忽略,但如果COUNT()函式中用的是星號( *),則不忽略。 

關於count 可以看我寫的另一篇,詳細分析了幾種count的使用和效能比較: SELECT COUNT 小結

MAX()和MIN()函式

MAX()返回指定列中的最大值,MIN()返回指定列中的最小值

 1 mysql> select * from user2;
 2 +----+--------+------+----------+-----+
 3 | id | name   | age  | address  | sex |
 4 +----+--------+------+----------+-----+
 5 |  1 | brand  |   21 | fuzhou   |   1 |
 6 |  2 | helen  |   20 | quanzhou |   0 |
 7 |  3 | sol    |   21 | xiamen   |   0 |
 8 |  4 | weng   |   33 | guizhou  |   1 |
 9 |  5 | selina |   25 | NULL     |   0 |
10 |  6 | anny   |   23 | shanghai |   0 |
11 |  7 | annd   |   24 | shanghai |   1 |
12 |  8 | sunny  | NULL | guizhou  |   0 |
13 +----+--------+------+----------+-----+
14 8 rows in set
15 
16 mysql> select max(age),min(age) from user2;
17 +----------+----------+
18 | max(age) | min(age) |
19 +----------+----------+
20 |       33 |       20 |
21 +----------+----------+
22 1 row in set 

 注意:同樣的,MAX()、MIN()函式忽略列值為NULL的行。

SUM函式

SUM()用來返回指定列值的和(總計) ,下面返回了所有年齡的總和,同樣的,忽略了null的值

 1 mysql> select * from user2;
 2 +----+--------+------+----------+-----+
 3 | id | name   | age  | address  | sex |
 4 +----+--------+------+----------+-----+
 5 |  1 | brand  |   21 | fuzhou   |   1 |
 6 |  2 | helen  |   20 | quanzhou |   0 |
 7 |  3 | sol    |   21 | xiamen   |   0 |
 8 |  4 | weng   |   33 | guizhou  |   1 |
 9 |  5 | selina |   25 | NULL     |   0 |
10 |  6 | anny   |   23 | shanghai |   0 |
11 |  7 | annd   |   24 | shanghai |   1 |
12 |  8 | sunny  | NULL | guizhou  |   0 |
13 +----+--------+------+----------+-----+
14 8 rows in set
15 
16 mysql> select sum(age) from user2;
17 +----------+
18 | sum(age) |
19 +----------+
20 | 167      |
21 +----------+
22 1 row in set

分組查詢

資料準備,假設我們有一個訂貨單表如下(記載使用者的訂單金額和下單時間):

 1 mysql> select * from t_order;
 2 +---------+-----+-------+--------+---------------------+------+
 3 | orderid | uid | uname | amount | time                | year |
 4 +---------+-----+-------+--------+---------------------+------+
 5 |      20 |   1 | brand | 91.23  | 2018-08-20 17:22:21 | 2018 |
 6 |      21 |   1 | brand | 87.54  | 2019-07-16 09:21:30 | 2019 |
 7 |      22 |   1 | brand | 166.88 | 2019-04-04 12:23:55 | 2019 |
 8 |      23 |   2 | helyn | 93.73  | 2019-09-15 10:11:11 | 2019 |
 9 |      24 |   2 | helyn | 102.32 | 2019-01-08 17:33:25 | 2019 |
10 |      25 |   2 | helyn | 106.06 | 2019-12-24 12:25:25 | 2019 |
11 |      26 |   2 | helyn | 73.42  | 2020-04-03 17:16:23 | 2020 |
12 |      27 |   3 | sol   | 55.55  | 2019-08-05 19:16:23 | 2019 |
13 |      28 |   3 | sol   | 69.96  | 2020-09-16 19:23:16 | 2020 |
14 |      29 |   4 | weng  | 199.99 | 2020-06-08 19:55:06 | 2020 |
15 +---------+-----+-------+--------+---------------------+------+
16 10 rows in set 

單欄位分組

即對於某個欄位進行分組,比如針對使用者進行分組,輸出他們的使用者Id,訂單數量和總額:

 1 mysql> select uid,count(uid),sum(amount) from t_order group by uid;
 2 +-----+------------+-------------+
 3 | uid | count(uid) | sum(amount) |
 4 +-----+------------+-------------+
 5 |   1 |          3 | 345.65      |
 6 |   2 |          4 | 375.53      |
 7 |   3 |          2 | 125.51      |
 8 |   4 |          1 | 199.99      |
 9 +-----+------------+-------------+
10 4 rows in set 

多欄位分組

即對於多個欄位進行分組,比如針對使用者進行分組,再對他們不同年份的訂單資料進行分組,輸出訂單數量和消費總額:

 1 mysql> select uid,count(uid) as nums,sum(amount) as totalamount,year from t_order group by uid,year;
 2 +-----+------+-------------+------+
 3 | uid | nums | totalamount | year |
 4 +-----+------+-------------+------+
 5 |   1 |    1 | 91.23       | 2018 |
 6 |   1 |    2 | 254.42      | 2019 |
 7 |   2 |    3 | 302.11      | 2019 |
 8 |   2 |    1 | 73.42       | 2020 |
 9 |   3 |    1 | 55.55       | 2019 |
10 |   3 |    1 | 69.96       | 2020 |
11 |   4 |    1 | 199.99      | 2020 |
12 +-----+------+-------------+------+
13 7 rows in set 

分組前的條件過濾:where

這個很簡單,就是再分組(group by)之前通過where關鍵字進行條件過濾,取出我們需要的資料,假設我們只要列出2019年8月之後的資料,源資料只有6條合格的,有兩條年份一樣被分組的:

 1 mysql> select uid,count(uid) as nums,sum(amount) as totalamount,year from t_order where time > '2019-08-01' group by uid,year;
 2 +-----+------+-------------+------+
 3 | uid | nums | totalamount | year |
 4 +-----+------+-------------+------+
 5 |   2 |    2 | 199.79      | 2019 |
 6 |   2 |    1 | 73.42       | 2020 |
 7 |   3 |    1 | 55.55       | 2019 |
 8 |   3 |    1 | 69.96       | 2020 |
 9 |   4 |    1 | 199.99      | 2020 |
10 +-----+------+-------------+------+
11 5 rows in set 

分組後的條件過濾:having

有時候我們需要再分組之後再對資料進行過濾,這時候就需要使用having關鍵字進行資料過濾,再上述條件下,我們需要取出消費次數超過一次的資料:

1 mysql> select uid,count(uid) as nums,sum(amount) as totalamount,year from t_order where time > '2019-08-01' group by uid,year having nums>1;
2 +-----+------+-------------+------+
3 | uid | nums | totalamount | year |
4 +-----+------+-------------+------+
5 |   2 |    2 | 199.79      | 2019 |
6 +-----+------+-------------+------+
7 1 row in set 

這邊需要注意區分where和having:

where是在分組(聚合)前對記錄進行篩選,而having是在分組結束後的結果裡篩選,最後返回過濾後的結果。

可以把having理解為兩級查詢,即含having的查詢操作先獲得不含having子句時的sql查詢結果表,然後在這個結果表上使用having條件篩選出符合的記錄,最後返回這些記錄,因此,having後是可以跟聚合函式的,並且這個聚集函式不必與select後面的聚集函式相同。

分組後的排序處理

order條件接在group by後面,也就是統計出每個使用者的消費總額和消費次數後,對使用者的消費總額進行降序排序的過程。

 1 mysql> select uid,count(uid) as nums,sum(amount) as totalamount from t_order group by uid;
 2 +-----+------+-------------+
 3 | uid | nums | totalamount |
 4 +-----+------+-------------+
 5 |   1 |    3 | 345.65      |
 6 |   2 |    4 | 375.53      |
 7 |   3 |    2 | 125.51      |
 8 |   4 |    1 | 199.99      |
 9 +-----+------+-------------+
10 4 rows in set
11 
12 mysql> select uid,count(uid) as nums,sum(amount) as totalamount from t_order group by uid order by totalamount desc;
13 +-----+------+-------------+
14 | uid | nums | totalamount |
15 +-----+------+-------------+
16 |   2 |    4 | 375.53      |
17 |   1 |    3 | 345.65      |
18 |   4 |    1 | 199.99      |
19 |   3 |    2 | 125.51      |
20 +-----+------+-------------+
21 4 rows in set 

分組後的limit 限制

limit限制關鍵字一般放在語句的最末尾,比如基於我們上面的搜尋,我們再limit 1,只取出消費額最高的那條,其他跳過。

1 mysql> select uid,count(uid) as nums,sum(amount) as totalamount from t_order group by uid order by totalamount desc limit 1;
2 +-----+------+-------------+
3 | uid | nums | totalamount |
4 +-----+------+-------------+
5 |   2 |    4 | 375.53      |
6 +-----+------+-------------+
7 1 row in set 

關鍵字的執行順序

我們看到上面那我們用了 where、group by、having、order by、limit這些關鍵字,如果一起使用,他們是有先後順序,順序錯了會導致異常,語法格式如下:

1 select cname from tname
2 where [原表查詢條件]
3 group by [分組表示式]
4 having [分組過濾條件]
5 order by [排序條件]
6 limit [offset,] count;

 

1 mysql> select uid,count(uid) as nums,sum(amount) as totalamount from t_order where time > '2019-08-01' group by uid having totalamount>100 order by totalamount desc limit 1;
2 +-----+------+-------------+
3 | uid | nums | totalamount |
4 +-----+------+-------------+
5 |   2 |    3 | 273.21      |
6 +-----+------+-------------+
7 1 row in set

 

總結

1、分組語法中,select後面出現的欄位 要麼是group by後面的欄位,要麼是聚合函式的列,其他型別會報異常:可以自己試試。

2、分組關鍵字的執行順序:where、group by、having、order by、limit,順序不能調換,否則會報異常:可以自己試試。

相關文章