先来看一个问题,如果需要返回供应商DLL01提供的产品数目,SQL如下:
select count(*) from Products where vend_id = ‘DLL01‘;
那么如果要返回每个供应商提供的产品数目呢?这时就可以使用分组将数据分为多个逻辑组,对每个组进行聚集计算。
select vend_id, count(*) as num_prods from Products group by vend_id;
注意,GROUP BY
必须出现在WHERE
之后,ORDER BY
之前。
再来看一个问题,如果需要检索出每个客户的订单数量,根据上面所学,SQL如下:
select cust_id, count(*) as orders from Orders group by cust_id;
现在有个新的问题,需要检索出两个订单以上的客户,怎么做?
像这样?
select cust_id, count(*) as orders from Orders group by cust_id where count(*) >=2;
很明显,这是错误写法,因为WHERE
是过滤指定的行,没有分组的概念。过滤分组需要使用HAVING
。
select cust_id, count(*) as orders from Orders group by cust_id having count(*) >=2;
可以这么理解,WHERE
在数据分组前进行过滤,HAVING
在数据分组后进行过滤。
select vend_id, count(*) as num_prods from Products where prod_price >= 4 group by vend_id having count(*) >=2;
最后再来看一个问题,
select order_num,count(*) as items from OrderItems group by order_num having count(*) >=3 order by items,order_num;
原文:https://www.cnblogs.com/xLI4n/p/10345910.html