where、having、group by、order by、count的使用注意

1_where、having、group by、order by的顺序

where、 group by、 having、 order by

2_group by的作用

注意事项:分组后只能对分组属性进行操作
错误举例:select name from table_name group by type
由于group by type ,所以分组属性是type,不能select name

在这里插入图片描述

3_where和group by的组合

先where进行按单个元组进行条件筛选,后通过group by对筛选后的集合进行分组

--选择库存编号大于10000并按种类分组
select type from repertory_record where repertory_id > 10000 group by type

在这里插入图片描述

4_group by和having的组合

先where进行按单个元组进行条件筛选,再使用group by 进行分组最后使用having对分组后的一个个集合进行操作

--先按照种类进行分组,再从这些组中挑选'杯子','电脑','耳机'这三类
select type from repertory_record group by type having type in ('杯子','电脑','耳机')

在这里插入图片描述

5_where、having、group by的组合使用

使用group by进行分组,再使用having对分组后的一个个集合进行操作

--先使用where筛选编号大于10000的记录,再使用group by进行按种类分组,最后使用having在已经分好组的集合中选择种类不是'杯子','电脑','耳机'这三类的记录
select type from repertory_record where repertory_id > 1000 group by type having type not in ('杯子','电脑','耳机')

6_count与group by的组合使用

在这里插入图片描述

--如上图所示为分组后的状态,分组后统计每个组的元组数目count(type)
select type,count(type) from repertory_record where repertory_id < 10004 group by type

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43907296/article/details/111032371