《MySQL必知必会》第十三章:分组数据
@author: Tobin
@date: 2019/10/28 22:32:57
关注GROUP BY和 HAVING子句
# 创建分组
SELECT vend_id , COUNT(*) AS num_prods
FROM products
GROUP BY vend_id;
#SELECT中,除了聚集语句之外,每个列都需要在GROUP BY语句中给出。
# GROUP BY 位于WHERE语句之后,ORDER BY语句之前。
# HAVING过滤分组,WHERE过滤行
SELECT vend_id , COUNT(*) AS num_prods
FROM products
GROUP BY vend_id
HAVING COUNT(*)>=2;
SELECT vend_id , COUNT(*) AS num_prods
FROM products
WHERE prod_price >=10
GROUP BY vend_id
HAVING COUNT(*)>=2;
# 使用ORDER BY 排序
SELECT order_num, SUM(quantity*item_price) AS ordertotal
FROM orderitems
GROUP BY order_num
HAVING SUM(quantity*item_price) >=50
ORDER BY ordertotal;