zoukankan      html  css  js  c++  java
  • Sql server 开窗函数over()的语法

    用法一:与ROW_NUMBER()函数结合用,给结果进行排序编号,如图:

    代码如下:

    SELECT ROW_NUMBER() over(order by RequiredDate) num
           ,* from  [Northwind].[dbo].[Orders]

    用法二:跟聚合函数一起使用,利用over子句的分组效率比group by子句的效率更高。

    在Northwind数据库的订单表Orders中查询"订单id","客户id","运费","所有订单的总数",“每一个客户的总运费”,“所有客户的总运费”,“每一个客户的平均运费”,“所有客户的平均运费”,"每一个客户所有订单中最大的运费","所有客户中最大运费","每一个客户所有订单中最小的运费","所有客户中最小运费",如下图:

    代码如下:

    复制代码
      SELECT  [OrderID] --订单id
          ,[CustomerID] --客户id
          ,[Freight] --运费
          ,COUNT(OrderID) over() as totalNum --一所有订单的总数
          ,SUM(Freight) over(partition by customerid) as cusTotalFreight --每一个客户的总运费
          ,SUM(Freight) over() as totalFreight --所有客户的总运费
          ,AVG(Freight) over(partition by customerid) as cusAvgFreight --每一个客户的平均运费
          ,AVG(Freight) over() as avgFreight --所有客户的平均运费
          ,MAX(Freight) over(partition by customerid) as cusMaxFreight --每一个客户所有订单中最大的运费
          ,MAX(Freight) over() as maxFreight --所有客户中最大运费
          ,MIN(Freight) over(partition by customerid) as cusMinFreight --每一个客户所有订单中最小的运费
          ,MIN(Freight) over() as minFreight --所有客户中最小运费
      FROM [Northwind].[dbo].[Orders]
    复制代码

    总结:运用开窗函数over()再结合聚合函数,可以使表格向右扩张,并进行一些数据的统计

  • 相关阅读:
    [ARC117F]Gateau
    [ARC117D]Miracle Tree
    [loj3504]支配
    [gym102511K]Traffic Blights
    [loj3501]图函数
    [loj3503]滚榜
    [loj3500]矩阵游戏
    [loj2135]幻想乡战略游戏
    [cf720D]Slalom
    [cf1349E]Slime and Hats
  • 原文地址:https://www.cnblogs.com/lip-blog/p/8295442.html
Copyright © 2011-2022 走看看