SQL必知必会-笔记(六)分组数据

为什么需要分组?

先来看一个问题,如果需要返回供应商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在数据分组后进行过滤。

  • 问题:检索出具有两个以上产品且价格大于等于4的供应商
  • 解:
select vend_id, count(*) as num_prods from Products where prod_price >= 4 group by vend_id having count(*) >=2;

最后再来看一个问题,

  • 问题:检索出包含3个或更多物品的订单号以及订购物品的数量,且按照订购物品的数量排序
  • 解:
select order_num,count(*) as items from OrderItems group by order_num having count(*) >=3 order by items,order_num;

猜你喜欢

转载自www.cnblogs.com/xLI4n/p/10345910.html