MySQL Learning Note (iv) GROUP by and having usage

Source: Internet
Author: User

Note: The field after select must either be included in group by or be included in the aggregate function after having a. 1. Group BY is a group query, and the general group by ISuse with aggregate functions

Group by has a principle that all columns following the Select Do not have columns that use aggregate functions and must appear behind group by (important)

For example, the following database tables are available:

A B
1 ABC
1 BCD

1 ASDFG

If you have the following query statement ( The statement is wrong, the reason is the preceding principle)

Select A b from table group by A

The intent of the query statement is to get the following results ( of course, just wishful)

A B
Abc
1 BCD

Asdfg

On the right 3 how to become one, so you need to use the aggregate function, as follows (the following is the correct way):

Select A,count (B) as Quantity from table group by A
So the result is
A Quantity
1 3

2. Having

The purpose of the WHERE clause is to remove rows that do not conform to the where condition before grouping the results of the query, that is, to filter the data before grouping, the condition cannot contain a clustering function, and the Where condition is used to display a particular row.

The HAVING clause is used to filter the groups that meet the criteria, that is, to filter the data after grouping, often including clustering functions, to display specific groups using the having condition , or to group by using multiple grouping criteria.

The HAVING clause is restricted to columns and aggregate expressions that are already defined in the SELECT statement. Typically, you need to reference an aggregate value by repeating an aggregate function expression in the HAVING clause, as you did in the SELECT statement. For example:

SELECT A count (b) from TABLE GROUP by A has COUNT (b) >2

MySQL Learning Note (iv) GROUP by and having usage

Related Article

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.