HAVE 語句是 SQL 中用于過濾分組后數據的子句,通常與 GROUP BY 和聚合函數一起使用
SELECT column_name(s), aggregate_function(column_name)
FROM table_name
GROUP BY column_name(s)
HAVING condition;
其中:
column_name(s)
:指定要從表中選擇的列名。aggregate_function(column_name)
:對選定列應用聚合函數(例如 COUNT、SUM、AVG、MIN 或 MAX)。table_name
:指定查詢的表名。GROUP BY column_name(s)
:根據指定的列對結果進行分組。HAVING condition
:設置分組后數據的篩選條件。以下是一個實際示例,該示例從 “orders” 表中選擇 “customer_id” 和每個客戶的訂單總數,但僅顯示訂單數量大于 10 的客戶:
SELECT customer_id, COUNT(*) as total_orders
FROM orders
GROUP BY customer_id
HAVING total_orders > 10;