T-SQL之SELECT语句的元素

  select id,name,count(distinct name) as namecount from  table1 where  id=1  
  group  by id,name having count(distinct name) having  name=''  order  by  id

如上述sql,在逻辑上按照下面的顺序进行执行:

1.from 2.where 3.group by 4.having  5.select  (5.1 over  5.2distinct  5.3top) 6.order by 

1.1from

  指定要查询的表名。

1.2  where

可以指定一个为此或逻辑表达式,从而过滤由from阶段返回 的行。

1.3 group by

这个阶段可以将前面查询到的数据按组进行组合。所以在select中后面使用到的属性,都要包括在group by后面,因为这个阶段是为了保证查询到的属性值作为一个组合是唯一的。

注意:所有的聚合函数都会忽略NULL值,只有count(*)除外,比如一列count1的值为10,20,NULL,10,10,60,那么count(*)=6,但是count(count1)=5.因为count1列只有5行已知值。还可以在聚合函数中指定distinct关键字。比如count( distinct count1)=4,sum(distinct count1)=90,avg( distinct count1)=90/3=30.

1.4having

having 关键字是在对行进行分组之后进行处理的,是指定对组进行过滤的谓词或逻辑表达式。

1.5 select

select用于指定需要在查询返回的结果集中包含的属性(列)。

原文地址:https://www.cnblogs.com/anjingdian/p/11594870.html