HAVING 子句用於篩選分組後的數據,語法為:SELECT aggregate_functions(column_name) FROM table_name GROUP BY column_name HAVING condition;。它可以篩選聚合函數、分組列、常數或運算子。例如,以下查詢篩選出訂單中至少包含3 件商品且總金額大於100 美元的群組:SELECT COUNT(DISTINCT order_id) AS order_count FROM orders GROUP BY cus
SQL 中HAVING 子句
HAVING 子句的作用:
HAVING 子句用於對分組後的資料進行篩選。它與 WHERE 子句類似,但用於篩選聚合結果,而不是篩選原始資料。
HAVING 子句的語法:
<code>SELECT aggregate_functions(column_name) FROM table_name GROUP BY column_name HAVING condition;</code>
#條件:
HAVING 子句中的條件可以包含下列內容:
HAVING 子句的用法:
#HAVING 子句可以用於多種場景,例如:
範例:
查詢符合下列條件的訂單:
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;注意:
- #HAVING 子句只能在GROUP BY 子句之後使用。
- HAVING 子句只能篩選聚合結果,不能篩選原始資料。
以上是sql中having怎麼用的詳細內容。更多資訊請關注PHP中文網其他相關文章!