SQL query example with count or sum as the condition (SQL Query count)

Source: Internet
Author: User

For example, the user_num table:



Example 1:Query the user that appears twice

Beginners often mistakenly think that the count () algorithm is directly used in the where statement. Obviously, this idea is wrong. The count () method cannot be used in the where clause, to solve the problem, we can use HAVING next to the group by clause as the condition restriction.
Incorrect practice: select * from user_num where count (user)> = 2 group by user;
Correct practice: select * from user_num group by user HAVING count (user)> = 2;
Explanation: HAVING is similar to WHERE and can be used to determine which records to select. The HAVING clause specifies in the SELECT statement which records have been grouped by group by clause are displayed. After group by combines records, HAVING displays any records that meet the HAVING clause GROUP.

Example 2:Query users whose num is greater than 10 for a single user

With prior experience, write the sum () method in the HAVING clause.
Correct practice: select * from user_num group by user HAVING sum (num)> 10;

Note: a having clause can contain up to 40 expressions. The expressions in the HAVING clause can be separated by and or.

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.