HAVING clause is used to filter grouped data. The syntax is: SELECT aggregate_functions(column_name) FROM table_name GROUP BY column_name HAVING condition;. It can filter on aggregate functions, grouping columns, constants or operators. For example, the following query filters out groups with at least 3 items in the order and a total amount greater than $100: SELECT COUNT(DISTINCT order_id) AS order_count FROM orders GROUP BY cus
The HAVING clause in SQL
#The role of the HAVING clause:
The HAVING clause is used to filter grouped data . It is similar to the WHERE clause, but is used to filter aggregated results rather than raw data.
The syntax of the HAVING clause:
<code>SELECT aggregate_functions(column_name) FROM table_name GROUP BY column_name HAVING condition;</code>
Conditions:
The conditions in the HAVING clause can include the following:
Usage of HAVING clause:
HAVING clause can be used in a variety of scenarios, for example:
Example:
Query orders that meet the following conditions:
SELECT COUNT(DISTINCT order_id) AS order_count
FROM orders
GROUP BY customer_id
HAVING SUM(total_amount) > 100 AND COUNT(DISTINCT product_id) >= 3;Note:
- The HAVING clause can only be used after the GROUP BY clause.
- HAVING clause can only filter aggregate results, not original data.
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!