HAVING clause is used to filter aggregate results. Its usage is: used after GROUP BY clause. Specify criteria to filter aggregated results. Use aggregate functions like SUM, AVG and grouping columns. It is often used to filter aggregated results that meet specific conditions, find groups that meet conditions, or further segment aggregated results. The difference with the WHERE clause: The HAVING clause acts after the grouping operation, while the WHERE clause acts before the grouping, and the filtering conditions are different for the aggregated results and the underlying data.
Usage of HAVING clause in SQL
HAVING clause is used to filter a set of aggregate results . It is used after the GROUP BY clause to filter the conditions of the aggregate results.
Grammar:
<code class="sql">SELECT 聚合函数(列) FROM 表名 GROUP BY 分组列 HAVING 条件;</code>
Usage:
Example:
<code class="sql">SELECT COUNT(*) AS 订单数 FROM 订单表 GROUP BY 客户编号 HAVING COUNT(*) > 10;</code>
This query counts the number of orders placed by each customer and only displays customers with orders greater than 10.
Use:
The HAVING clause is often used in the following scenarios:
and the WHERE clause:
The main difference between the HAVING clause and the WHERE clause is:
Note:
The above is the detailed content of How to use having in sql. For more information, please follow other related articles on the PHP Chinese website!