mysql group by having 实例代码
程序员文章站
2023-12-17 19:17:58
mysql group by having 实例
注意:使用group by的时候,select子句中的列名必须为分组列。 如下实例必须包括name列名,因为name是作...
mysql group by having 实例
注意:使用group by的时候,select子句中的列名必须为分组列。 如下实例必须包括name列名,因为name是作为group by分组的条件。
实例:
我的数据库中有一张员工工作记录表,表中的数据库如下:
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)
需求一:现在我需要查找出每个员工工作了多少天,这时就需要用到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)
需求二:我现在要查找工作天数大于一天的所有员工,这个时候就需要用到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)
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!