Query sample with Count or sum in SQL (SQL query count) _mssql

Source: Internet
Author: User

For example User_num table:



Example 1: a query that has occurred 2 times user

Often beginners mistakenly assume that the count () algorithm is used directly in the where statement, which is clearly wrong, and the count () method cannot be used in the WHERE clause, and to solve the problem, we can use the having to make conditional restrictions after the GROUP BY clause.
Error procedure: SELECT * from User_num where count (user) >=2 group by user;
Correct practice: SELECT * from User_num GROUP by user has count (user) >=2;
Explanation: Having is similar to where it can be used to determine which records to select. The HAVING clause is specified in the SELECT statement, showing which records are grouped by the GROUP BY clause. After group by combines records, having displays any records that are grouped by the GROUP BY clause that conform to the HAVING clause.

Example 2: querying a single user's num sum of more than 10 users

With the previous experience, the sum () method is written in the HAVING clause.
Correct practice: SELECT * from User_num GROUP by user has sum (num) >10;

NOTE: A HAVING clause can contain up to 40 expressions, and the expression of a HAVING clause may be split with and and OR.

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.