窗口函数 SELECT - OVER Clause (Transact-SQL)

Posted Chuck Lu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了窗口函数 SELECT - OVER Clause (Transact-SQL)相关的知识,希望对你有一定的参考价值。

https://docs.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql

Determines the partitioning and ordering of a rowset before the associated window function is applied.

That is, the OVER clause defines a window or user-specified set of rows within a query result set.

A window function then computes a value for each row in the window.

You can use the OVER clause with functions to compute aggregated values such as moving averages, cumulative累积的 aggregates, running totals, or a top N per group results.

 

分组

PARTITION BY
Divides the query result set into partitions.

The window function is applied to each partition separately and computation restarts for each partition.  

 

根据什么进行分组

alue_expression
Specifies the column by which the rowset is partitioned.

value_expression can only refer to columns made available by the FROM clause.

value_expression cannot refer to expressions or aliases in the select list.

value_expression can be a column expression, scalar subquery, scalar function, or user-defined variable.

 

 

<ORDER BY clause>
Defines the logical order of the rows within each partition of the result set.

That is, it specifies the logical order in which the window functioncalculation is performed.

 

order_by_expression
Specifies a column or expression on which to sort.

order_by_expression can only refer to columns made available by the FROM clause.

An integer cannot be specified to represent a column name or alias.  

 

实战

WITH temp2
AS ( SELECT Id ,
            [number] ,
            ROW_NUMBER() OVER ( ORDER BY ( SELECT 1 )) AS SNO
     FROM   dbo.TestPartition )
SELECT temp2.Id ,
       temp2.number ,
       SUM(number) OVER ( PARTITION BY temp2.Id
                          ORDER BY temp2.SNO ) AS number 累计值
FROM   temp2

 

以上是关于窗口函数 SELECT - OVER Clause (Transact-SQL)的主要内容,如果未能解决你的问题,请参考以下文章

SQLSQL常见窗口函数整理汇总大全(用到over的场景)

Oracle over函数

(Presto) 窗口函数“OVER”子句中“ROWS BETWEEN”和“RANGE BETWEEN”的区别

sql over表示啥意思

窗口函数/解析函数

Oracle分析函数