sql常见的知识(一)order by 和 group by

一:order  by 和 group by

1:order by:排序,从数据库表中获取到一个或多个字段按照升序( ascending order) 或降序(descending)排序。

 select * from 表 where 条件 order by 字段a ASC 。 

 select * from 表 where 条件 order by 字段b DESC 。

 select *from 表 where [condition] order by 字段a, 字段b,...字段n, ASC / DESC

(最前面的字段优先级最高,即字段a的优先级最高,先按字段a排列后字段a重复的再按字段b排列)。

若没有严格进行首字母排序(第一行),还可以使用convert _to函数输出一下

sql常见的知识(一)order by 和 group by_第1张图片

2:group by:对相同的数据进行分组,通常与聚合函数(sum()、count()、avg()、string_agg())放在一起试用。放在order by的前面。

解析group by的使用方式:

 select  a from 表。(会有重复数据出现)

 select a from 表 group by a;  (会去掉重复的数据,对a数据进行分组。)

若有若干个字段的查询条件:

 select a ,b from 表

 select a ,sum(b) from 表 group by a;(因为会去掉重复的a,所以对应的b必须进行聚合。)

注意:若想对b进行条件过滤,则需使用 having。原因,聚合函数是针对结果集的,where 是在查询出结果集之前运行的。所以在where之后不能接聚合函数进行条件过滤。例如:

 select a,sum(b) from 表 group by a HAVING sum(b) > 10;

也可在group by 之前使用 where ,即先对结果集进行过滤,在分组。

所以where- group by-having-order by: 即先对select xx from xx的记录集合用where进行筛选,然后再使用group by 对筛选后的结果进行分组 使用having字句对分组后的结果进行筛选,最后进行排序。

你可能感兴趣的:(sql)