MySQL HAVING
阿新 • • 發佈:2018-12-19
簡介
HAVING 字句 主要用於經過Group by之後SELECT中的資料的篩選。
HAVING子句通常與GROUP BY子句一起使用,以根據指定條件過濾組。如果省略了GROUP BY子句,則HAVING子句的行為與WHERE子句類似
注意,HAVING子句將篩選條件應用於每一組行,而WHERE子句將篩選條件應用於每一行
MySQL HAVING 字句例項
有如下示例表:
You can use GROUP BY clause to get order numbers, the number of items sold per order, and total sales for each:
SELECT
ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceeach*quantityOrdered) AS total
FROM
orderdetails
GROUP BY ordernumber;
查詢結果:
Now, you can find which order has total sales greater than 1000 by using the HAVING clause as follows:
SELECT ordernumber, SUM(quantityOrdered) AS itemsCount, SUM(priceeach*quantityOrdered) AS total FROM orderdetails GROUP BY ordernumber HAVING total > 1000;
Suppose you want to find all orders that have shipped and total sales greater than 1500, you can join the orderdetails table with the orders table using the INNER JOIN clause and apply a condition on status column and total aggregate as shown in the following query:
SELECT a.ordernumber, status, SUM(priceeach*quantityOrdered) total FROM orderdetails a INNER JOIN orders b ON b.ordernumber = a.ordernumber GROUP BY ordernumber, status HAVING status = 'Shipped' AND total > 1500;
HAVING子句僅僅用於當你用GROUP BY 字句來生成高階報告;
例如,您可以使用HAVING子句來回答統計問題,比如查詢本月、本季度或今年的總銷售額超過10K的訂單數量。