Get the App
SLTechnology News&Howtos  ›  Database  › 

What is the example of a query conditional on count or sum in sql

Shulou Source: shulou.com Published: 2022-05-31 12:53:06 10月09日 Update

sql count or sum for the condition of the query example is what, I believe that many inexperienced people are helpless, for this reason this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

For example, user_num table:

Example 1: Query user that has appeared twice

Beginners often mistakenly think that count() is used directly in where statements. Obviously, this idea is wrong. Count() cannot be used in where clauses. To solve the problem, we can use HAVING after group by clauses to make conditional restrictions.

Error: select * from user_num where count(user)>=2 group by user; Correct: select * from user_num group by user HAVING count(user)>=2 ;

Explanation: HAVING is similar to WHERE and can be used to decide which records to select. The HAVING clause specifies in the SELECT statement that records grouped with the GROUP BY clause are displayed. After the records are grouped by GROUP BY, HAVING displays any records grouped by the GROUP BY clause that match the HAVING clause.

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

With the previous experience, write the sum() method in the HAVING clause. Correct: select * from user_num group by user HAVING sum(num)>10 ; Note: A HAVING clause can only contain up to 40 expressions, and the expressions of the HAVING clause can be separated by AND and OR.

After reading the above content, do you know what kind of query example is conditional on count or sum in sql? If you still want to learn more skills or want to know more related content, welcome to pay attention to the industry information channel, thank you for reading!

Tags: Clause query method condition practice error problem example content more user experience expression statement grouping helpless for this reason middle finger between beginners Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB NVidia Apple Microsoft Shulou Technology