Issue with Window Function in MSSQL 2008 R2

人走茶凉 提交于 2020-01-01 16:34:49

问题


I am receving execution error in following sql script.

Select TOP 1 Percent a.accode,a.voucherdate,a.credit,a.Debit,
    SUM(a.Debit) Over (Order By [a.accode],[a.voucherdate] ) as rdr 

    from VoucherMain as a 
    Order By a.accode,a.voucherdate

Error Message

Incorrect syntax near 'order'.

Can anyone tell me what's wrong with the script syntext?


回答1:


The problem is that you need SQL Server 2012 and above. Okay, I added the "and above" for future visitors, but compare 2008 OVER CLAUSE with 2012 OVER CLAUSE.

The 2008 version has this important note:

When used in the context of a ranking window function, <ORDER BY Clause> can only refer to columns made available by the FROM clause. An integer cannot be specified to represent the position of the name or alias of a column in the select list. <ORDER BY Clause> cannot be used with aggregate window functions.




回答2:


In SQL Server 2008, you can only use the OVER clause to partition aggregate functions, not apply an order:

Ranking Window Functions < OVER_CLAUSE > :: = OVER ( [ PARTITION BY value_expression , ... [ n ] ] < ORDER BY_Clause> )

Aggregate Window Functions < OVER_CLAUSE > :: = OVER ( [ PARTITION BY value_expression , ... [ n ] ] )

Note that there's no <ORDER BY Clause> for the aggregates.



来源:https://stackoverflow.com/questions/12686140/issue-with-window-function-in-mssql-2008-r2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!