mysql group by having 實例
注意:使用group by的時候,SELECT子句中的列名必須為分組列。 如下實例必須包括name列名,因為name是作為group by分組的條件。
實例:
我的數(shù)據(jù)庫中有一張員工工作記錄表,表中的數(shù)據(jù)庫如下:
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)
需求一:現(xiàn)在我需要查找出每個員工工作了多少天,這時就需要用到group by語句:
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)
需求二:我現(xiàn)在要查找工作天數(shù)大于一天的所有員工,這個時候就需要用到group by having語句
mysql> SELECT name, COUNT(*)
-> FROM employee_tbl
-> GROUP BY name having COUNT(*)>1 ;
+------+----------+
| name | COUNT(*) |
+------+----------+
| Jack | 2 |
| Zara | 2 |
+------+----------+
2 rows in set (0.04 sec)
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
您可能感興趣的文章:- 淺談mysql數(shù)據(jù)庫中的using的用法
- Mysql之EXPLAIN顯示using filesort介紹
- mysql中g(shù)roup by與having合用注意事項分享
- MySql中having字句對組記錄進行篩選使用說明
- Mysql中order by、group by、having的區(qū)別深入分析
- mysql having用法解析
- MySQL中無GROUP BY情況下直接使用HAVING語句的問題探究
- MySQL無GROUP BY直接HAVING返回空的問題分析
- MySQL中USING 和 HAVING 用法實例簡析