首页 > 数据库技术 > 详细

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

时间:2019-02-01 16:44:16      阅读:163      评论:0      收藏:0      [点我收藏+]

为什么需要分组?

先来看一个问题,如果需要返回供应商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;

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

原文:https://www.cnblogs.com/xLI4n/p/10345910.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!