zoukankan      html  css  js  c++  java
  • 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 将所有的瞬间按顺序划分为几块,每一块进行排序

    查询效果示例:

    3.运算符优先级:

    1、()
    2、 *、/、%
    3、 +、-
    4、比较运算符
    5、not
    6、and
    7、between、in、like、or
    8、=

    4.CASE表达式:

    示例:

    select
    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   join /right join 

    全连接--显示符合条件的数据行,同时显示左右不符合条件的数据行,相应的左右两边显示NULL,即显示左连接、右连接和内连接的并集 full 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

    示例:

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

    select SalaryPayingEmployeeId,costType,cost
    from #temp
    unpivot(cost for costType in([300],[301],[302])) as U;

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

     8.临时表

    可以使用临时表的场合:
    1、需要把中间结果临时保存起来,以供以后查询这些临时数据
    2、需要多次访问一个开销昂贵的处理结果
    示例:此处是一个简单查询,仅展示临时表的操作

    select id,name,UserName
    into #temp
    from dbo.SystemUsers where Name like '%a%';

    select * from dbo.#temp;
    drop table #temp;

    全局临时表采用两个##

  • 相关阅读:
    java获取本机IP和主机名
    SSH框架总结(框架分析+环境搭建+实例源代码下载)
    Centos7安装mysql8教程
    jquery 操作HTML data全局属性缓存的坑
    mysql协议分析2---认证包
    mysql协议分析1---报文的格式和基本类型
    TCP三次握手抓包理解
    java读写文件小心缓存数组
    spring 事务隔离级别导致的bug
    mysql 不同版本下 group by 组内排序的差异
  • 原文地址:https://www.cnblogs.com/luoxiaoxiao102/p/15169780.html
Copyright © 2011-2022 走看看