Nilkanth Desai
Nilkanth Desai

Reputation: 71

Issue with Window Function in SQL Server 2008 R2

I get an 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 my syntax?

Upvotes: 3

Views: 3422

Answers (2)

RichardTheKiwi
RichardTheKiwi

Reputation: 107826

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.

Upvotes: 6

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239824

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.

Upvotes: 3

Related Questions