Sql 中having 和where的区别 SQL hardest question What is the difference between the WHERE and HAVING claus

来源:互联网 发布:论文数据研究方法 编辑:程序博客网 时间:2024/05/11 03:02



在一个含有group by where 和having的sql语句中,这三个语句执行的顺序:

1、先执行where找到符合条件的数据

2、执行group by子句将数据分组,group by子句中的select的返回字段中要么出现在group by后面的字段中,要么是聚合函数。

3、执行having对分组过滤不符合条件的组,having 后面的字段只能从 group by 返回的字段中选择。

举例说明:

 create TABLE Table1
    (
        ID int identity(1,1) primary key NOT NULL,   
        classid int, 
        sex varchar(10),
        age int, 
    ) 

查询table表查询每一个班级中年龄大于20,性别为男的人数
select COUNT(*)as '>20岁人数',classid  from Table1 where sex='男' group by classid,age having age>20 

select 只能是聚合函数和group by 后面的字段,

having 只能从select 中的字段选择


总结  

where在group by之前执行,过滤数据之后再分组

having 在group by后执行,过滤分组




0 0