MySql学习笔记(四) —— 数据的分组

前面介绍的聚集函数只是用来计算行数,平均数,最大值,最小值而不用检索所有数据。通过count()函数,我们可以计算生产商1003提供的产品数目,但如果我要查询所有生产商提供的商品数,这就需要进行分组查询。

1.创建分组:使用group by 关键字

select vend_id,count(*) as num_prods from products group by vend_id; --查询所有生产商生产的商品数

group by 要在where子句后,order by 子句前。

2.过滤分组:使用 having 关键字

针对上个场景,如果要找出提供的商品数大于5的生产商

select vend_id count(*) as num_prods from products group by vend_id having count(*)>5;

这里要说明一下:where 是对行进行过滤;count 是对分组进行过滤。where子句可以用count替代。当然有时也要这两个在一起使用。

我们在改变一下需求,如果我们要找出提供的商品数大于5,并且商品价格小于10的生产商。这样我们就先用where子句过滤掉大于10的商品,在进行分组统计

select vend_id count(*) as num_prods from products where prod_price =<10 group by vend_id having count(*)>5;

需求二:检索总计订单价格大于等于50的订单的订单号和总计订单价格。

select order_num,sum(quantity*item_price) as ordertoal from orderitems group by order_num having sum(quantity*item_price)>50 order by ordertoal;

3.select子句及其顺序

select--->from--->where--->group by--->having--->order by--->limit

原文地址:https://www.cnblogs.com/love-Stefanie/p/6894780.html