Oracle數據庫中的HAVING子句主要用于對分組后的結果進行篩選。它通常與GROUP BY子句一起使用,以限制分組后的數據集。以下是一些HAVING子句的應用場景:
SELECT product_id, SUM(sales_amount) AS total_sales
FROM sales_table
GROUP BY product_id
HAVING total_sales > 1000;
SELECT department_id, AVG(salary) AS avg_salary
FROM employee_table
GROUP BY department_id
HAVING avg_salary > 5000;
SELECT customer_id, COUNT(order_id) AS order_count
FROM orders_table
GROUP BY customer_id
HAVING order_count > 3;
需要注意的是,HAVING子句與WHERE子句的區別在于,WHERE子句在分組前對記錄進行篩選,而HAVING子句在分組后對分組結果進行篩選。此外,HAVING子句可以使用聚合函數,而WHERE子句則不能。