MySQL GROUP BY

可使用GROUP BY組值一列,而且若是願意的話,能夠將該列進行計算。使用COUNT,SUM,AVG等功能的分組列。mysql

要了解GROUP BY子句考慮的EMPLOYEE_TBL的的表具備如下記錄:sql

mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id   | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|    1 | John | 2007-01-24 |                250 |
|    2 | Ram  | 2007-05-27 |                220 |
|    3 | Jack | 2007-05-06 |                170 |
|    3 | Jack | 2007-04-06 |                100 |
|    4 | Jill | 2007-04-06 |                220 |
|    5 | Zara | 2007-06-06 |                300 |
|    5 | Zara | 2007-02-06 |                350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)

如今,假設根據上表,咱們但願計算每一位員工工做的天數。
若是咱們將編寫一個SQL查詢,以下所示,那麼咱們將獲得下面的結果:函數

 

mysql> SELECT COUNT(*) FROM employee_tbl;
+---------------------------+
| COUNT(*)                  |
+---------------------------+
| 7                         |
+---------------------------+

可是,這不是咱們的目的服務,咱們要顯示輸入的每一個人單獨的頁面總數。這是經過使用聚合函數一塊兒用GROUP BY子句以下:date

mysql> SELECT name, COUNT(*)
    -> FROM   employee_tbl 
    -> GROUP BY name;
+------+----------+
| name | COUNT(*) |
+------+----------+
| Jack |        2 |
| Jill |        1 |
| John |        1 |
| Ram  |        1 |
| Zara |        2 |
+------+----------+
5 rows in set (0.04 sec)

咱們將看到更多的功能,其餘功能相關的GROUP BY如SUM,AVG等。查詢

相關文章
相關標籤/搜索