---
title: "Oracle学习笔记----group by, having等语句的执行顺序"
author: "glutinit"
date: "2011-11-08T13:06:12Z"
tags: []
categories: ["数据库"]
slug: "oracle-group-by-having"
draft: false
lastmod: "2011-11-08T13:06:12Z"
id: 1242750
url: "https://glutinit.iteye.com/blog/1242750"
---

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. 为每个组计算分组函数的结果；
4. 根据having子句筛选组；
5. 根据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(*)也是分组函数