group by 和 having(转载)

文章地址:http://www.cnblogs.com/wang-123/archive/2012/01/05/2312676.html

--group by 和having 解释:前提必须了解sql语言中一种特殊的函数:聚合函数,
--例如SUM, COUNT, MAX, AVG等。这些函数和其它函数的根本区别就是它们一般作用在多条记录上。
--WHERE关键字在使用集合函数时不能使用,所以在集合函数中加上了HAVING来起到测试查询结果是否符合条件的作用。
 create TABLE Table1
    (
        ID int identity(1,1) primary key NOT NULL,  
        classid int,
        sex varchar(10),
        age int,
    )
   
--添加测试数据
    Insert into Table1 values(1,'男',20)
    Insert into Table1 values(2,'女',22)
    Insert into Table1 values(3,'男',23)
    Insert into Table1 values(4,'男',22)
    Insert into Table1 values(1,'男',24)
    Insert into Table1 values(2,'女',19)
    Insert into Table1 values(4,'男',26)
    Insert into Table1 values(1,'男',24)
    Insert into Table1 values(1,'男',20)
    Insert into Table1 values(2,'女',22)
    Insert into Table1 values(3,'男',23)
    Insert into Table1 values(4,'男',22)
    Insert into Table1 values(1,'男',24)
    Insert into Table1 values(2,'女',19


--举例子说明:查询table表查询每一个班级中年龄大于20,性别为男的人数
select COUNT(*)as '>20岁人数',classid  from Table1 where sex='男' group by classid,age having age>20
--需要注意说明:当同时含有where子句、group by 子句 、having子句及聚集函数时,执行顺序如下:
--执行where子句查找符合条件的数据;
--使用group by 子句对数据进行分组;对group by 子句形成的组运行聚集函数计算每一组的值;最后用having 子句去掉不符合条件的组。
--having 子句中的每一个元素也必须出现在select列表中。有些数据库例外,如oracle.
--having子句和where子句都可以用来设定限制条件以使查询结果满足一定的条件限制。
--having子句限制的是组,而不是行。where子句中不能使用聚集函数,而having子句中可以。

原文地址:https://www.cnblogs.com/davidwang456/p/2981928.html