- select xxx_name, count(*) as counter
- from table_y
- where where_condition
- group by xxx_name
- having having_condition
- order by zzz
当我们看到一个类似上述的包含了where, group by, having, order by等关键字的SQL时,我们要首先要知道其执行顺序是怎样的,才能判断出其所表达的含义;
下面列出其执行顺序:
1. 根据where子句选择行;
2. 根据group by 子句组合行;
3. 根据having子句筛选组;
4. 根据order by子句中的分组函数的结果对组进行排序,order by必须使用分组函数或者使用Group by子句中指定的列;
下面看一个例子:
- select CategoryName, count(*), AVG(Rating)
- from BOOKSHELF
- where Rating>1
- group by CategoryName
- having CategoryName like 'A%'
- order by count(*) desc
1.基于Where Rating>1 筛选出符合条件的行;
2.基于group by CategoryName 对筛选的结果进行分组;
3.为每个CategoryName组计算Count(*)
4. 基于having CategoryName like 'A%'留下符合条件的组
5. 根据order by 的条件对剩下的行组进行排序,SQL中的count(*)也是分组函数