Home > Database > Mysql Tutorial > mysql group by having 使用实例

mysql group by having 使用实例

WBOY
Release: 2016-06-01 09:58:24
Original
1155 people have browsed it

注意:使用group by的时候,SELECT子句中的列名必须为分组列。 如下实例必须包括name列名,因为name是作为group by分组的条件。

实例:

我的数据库中有一张员工工作记录表,表中的数据库如下:

<code class="language-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)</code>
Copy after login

需求一:现在我需要查找出每个员工工作了多少天,这时就需要用到group by语句:

<code class="language-sql">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)</code>
Copy after login

需求二:我现在要查找工作天数大于一天的所有员工,这个时候就需要用到group by having语句

<code class="language-sql">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)</code>
Copy after login

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template