一、GROUP BY 分組
SELECT
c1, c2,..., cn, aggregate_function(ci)
FROM
table
WHERE
where_conditions
GROUP BY c1 , c2,...,cn;
語句執行順序

將訂單狀態的值分組
SELECT
status
FROM
orders
GROUP BY status;
與聚合函數一起使用
每種狀態下的訂單數量
SELECT
status, COUNT(*)
FROM
orders
GROUP BY status;
所有訂單的總金額
SELECT
status,
SUM(quantityOrdered * priceEach) AS amount
FROM
orders
INNER JOIN orderdetails
USING (orderNumber)
GROUP BY
status;
查詢返回訂單號和每個訂單的總金額
SELECT
orderNumber,
SUM(quantityOrdered * priceEach) AS total
FROM
orderdetails
GROUP BY
orderNumber;
查詢獲取每年的總銷售額
SELECT
YEAR(orderDate) AS year,
SUM(quantityOrdered * priceEach) AS total
FROM
orders
INNER JOIN orderdetails
USING (orderNumber)
WHERE
status = 'Shipped'
GROUP BY
YEAR(orderDate);
過濾由GROUP BY子句返回的組,使用having
SELECT
YEAR(orderDate) AS year,
SUM(quantityOrdered * priceEach) AS total
FROM
orders
INNER JOIN orderdetails
USING (orderNumber)
WHERE
status = 'Shipped'
GROUP BY
year
HAVING
year > 2003;
標准SQL不允許您在GROUP BY子句中使用別名,但是MySQL支持這一點
SELECT
YEAR(orderDate) AS year,
COUNT(orderNumber)
FROM
orders
GROUP BY
year;
MySQL還允許您按升序或降序對組進行排序,而標准SQL則不允許
SELECT
status,
COUNT(*)
FROM
orders
GROUP BY
status DESC;
二、HAVING
用於為一組行或集合指定過濾條件
SELECT
select_list
FROM
table_name
WHERE
search_condition
GROUP BY
group_by_expression
HAVING
group_condition;
語句執行順序

獲取訂單號,每個訂單售出的商品數以及每個商品的總銷售額
SELECT
ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceeach*quantityOrdered) AS total
FROM
orderdetails
GROUP BY ordernumber;
訂單的總銷售額大於1000
SELECT
ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceeach*quantityOrdered) AS total
FROM
orderdetails
GROUP BY
ordernumber
HAVING
total > 1000;
HAVING使用OR 或者 AND
總金額大於1000且包含多個600項目的訂單:
SELECT
ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceeach*quantityOrdered) AS total
FROM
orderdetails
GROUP BY ordernumber
HAVING
total > 1000 AND
itemsCount > 600;
