Mysql group by having instance code, mysqlhaving

Source: Internet
Author: User

Mysql group by having instance code, mysqlhaving

Mysql group by having instance

Note:When using group by, the column name in the SELECT clause must be a group column. The following instance must include the name column, because name is a condition for group.

Instance:

My database has an employee work record table. The database in the table is as follows:

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)

Requirement 1: Now I need to find out how many days each employee has worked, and then I need to use the group by statement:

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)

Requirement 2: I want to find all employees who work more than one day now. In this case, the group by having statement is used.

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)

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.