天天看点

T-SQL

1.sql语句查询顺序

select ...

from ...

where ...

group by ...

having ...

order by ...

sql语句执行顺序

from

where

group by

having

select

over

distinct

top

order by

注意:1.如果引用不在group by列表中出现的属性,而且也没有将其作为group by子句之后的任何子句中聚合函数的输入,sql server引擎将会报错

           2.支持order by子句指定没有在select子句中出现过的元素,但是,如果指定了distinct后,order by子句就被限制为只能选取在select列表中出现的那些元素。

2.over支持的四种排名函数:row_number、rank、dense_rank、ntile

select orderid,custid,val,

row_number() over(order by val) as rownum,

rank() over(order by val) as rank,

dense_rank() over(order by val) as dense_rank,

ntile(1000) over(order by val) as ntile

from salas.ordervalues

order by val;

看下区别:row_number  所有的数据顺序排序

                  rank   顺序排序,遇到同名的,则相同排名,会空出下一个排名

                  dense_rank   顺序排序,遇到同名的,则相同排名,但不会空出下一个排名

                  ntile 将所有的瞬间按顺序划分为几块,每一块进行排序

查询效果示例:

T-SQL

3.运算符优先级:

1、()

2、 *、/、%

3、 +、-

4、比较运算符

5、not

6、and

7、between、in、like、or

8、=

4.CASE表达式:

示例:

case IsDeleted

  when 1 then '已删除'

  when 0 then '未删除'

else ''

end as idName,

case

  when id < 100 then 'less then 100'

  when id between 100 and 300 then 'between 100 and 300'

  when id > 300 then 'more then 300'

  else 'unknown'

end as idType

from dbo.SystemUsers

order by UserName;

5.join(ANSI标准)

JOIN 三种联接:

交叉联接---笛卡尔积     cross join

内联接---笛卡尔积、过滤    inner  join

外联接---笛卡尔积、过滤、添加外部行    left  outer join

6.使用PIVOT运算符进行透视转换

select SalaryPayingEmployeeId, [300], [301],[302] from

(select SalaryPayingEmployeeId,costtype,cost from SalaryPayingItems

where IsDeleted=0 and SalaryPayingEmployeeId='45D0BE76-AC43-4942-9D5B-AA4DDA86BAD7') tspipivot

Pivot(sum( tspipivot.cost) for tspipivot.costtype in ([300],[301],[302])

) as tspipivot

T-SQL

7.使用unpivot运算符进行逆透视转换

select SalaryPayingEmployeeId,costType,cost

from #temp

unpivot(cost for costType in([300],[301],[302])) as U;

示例:采用刚才转换后的表再转回去

T-SQL

 8.临时表

可以使用临时表的场合:

1、需要把中间结果临时保存起来,以供以后查询这些临时数据

2、需要多次访问一个开销昂贵的处理结果

示例:此处是一个简单查询,仅展示临时表的操作

select id,name,UserName

into #temp

from dbo.SystemUsers where Name like '%a%';

select * from dbo.#temp;

drop table #temp;

全局临时表采用两个##