Note on the use of where, having, group by, order by, and count

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

where、 group by、 having、 order by

The role of 2_group by

Note: You can only operate on group attributes after grouping.
Example of error: select name from table_name group by type
Because group by type, the group attribute is type, and you cannot select name

Insert picture description here

Combination of 3_where and group by

First where to perform conditional filtering by a single tuple , and then group by group by to group the filtered collection

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

Insert picture description here

4_group by and having a combination

First where to perform conditional filtering by a single tuple , then use group by for grouping , and finally use having to operate on the grouped collections

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

Insert picture description here

Combination of 5_where, having, group by

Use group by to group , and then use having to operate on the grouped collections

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

Combination of 6_count and group by

Insert picture description here

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

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43907296/article/details/111032371