特殊SQL语法

1、SELECT C,  SUM()  OVER (PARTITION BY A, B) FROM TABLE 条件汇总

2、RANK()函数,返回结果集分区内指定字段的值的排名

  如:Select rank() over(order by s_score desc) as 名次,s_class,s_id,s_score from s_score

3、列转行(UNPIVOT)、行转列(PIVOT)

4、STUFF(expression_to_be_searched varchar, starting_position int, number_of_chars int, replacement_expression varchar):用另一个子字符串替换一个子字符串,类似          replace函数

5、FOR XML PATH(‘’) 

      SELECT a.AccWarehouseNo FROM accWarehouse a for xml path('GAME')   

    <GAME>
      <AccWarehouseNo>AW01010001</AccWarehouseNo>
    </GAME>

  SELECT STUFF(a.AccWarehouseNo, 1, 0, '') FROM accWarehouse a for xml path('GAME')

  <GAME>AW01010001</GAME>


6、Rank()和ROW_NUMBER()

      Rank():生产连续ID,即使一样数据排名也不一样

      SELECT DEPTNO, STDDEPTNO, RANK() OVER(PARTITION BY DEPTNO ORDER BY STDDEPTNO ) FROM accWarehouse 

      ROW_NUMBER():生产不连续ID,即一样数据排名一样

      SELECT DEPTNO, STDDEPTNO, ROW_NUMBER() OVER(PARTITION BY DEPTNO ORDER BY STDDEPTNO ) FROM accWarehouse 

7、分页

   1)、使用ROW_NUMBER()

      2)、OFFSET/FETCH NEXT:对应LINQ的Skip()和Take(),list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList()

     SELECT * FROM TABLE ORDER BY A OFFSET ((pageIndex - 1) * pageSize) ROWS FETCH NEXT pageSize ROWS ONLY 

 

posted @ 2023-03-28 16:02  瘋孑  阅读(26)  评论(0编辑  收藏  举报