SQL Server 2012: sum over order by gives error Incorrect syntax near 'order'

僤鯓⒐⒋嵵緔 提交于 2021-02-07 22:38:58

问题


declare @t table (cid int, amount int, cname varchar)

insert into @t 
values (6, 20, 'C'), (7, 30, 'C'), (8, 10, 'C'), (9, 10, 'D')

select 
    sum(amount) over (partition by cname order by cid),
    *
from @t

Throws an error:

Incorrect syntax near 'order'.

https://msdn.microsoft.com/en-us/library/ms187810.aspx

Isn't sum over order by supported in SQL Server 2012? If I remove order by and use only partition by it works but for 'C' I get 60 for all rows. I want to get running total.

More info:

  • Microsoft SQL Server Management Studio 11.0.2100.60
  • Microsoft Analysis Services Client Tools 11.0.2100.60
  • Microsoft Data Access Components (MDAC) 6.1.7601.17514

Database option -> compatibility level only shows 2000, 2005 and 2008, with 2008 selected.

Trying to run

ALTER DATABASE database_name 
SET COMPATIBILITY_LEVEL = 110

Throws an error:

Valid values of the database compatibility level are 80, 90, or 100.


回答1:


Cumulative sums are not supported until SQL Server 2012+. Presumably, you are using SQL Server 2005 or 2008 or your compatibility setting is set to 105 or less (see here).

In these versions, you can use outer apply:

select t.*, s.amount
from @t t outer apply
     (select sum(t2.amount) as amount
      from @t t2
      where t2.cname = t.cname and t2.cid <= t.cid
     ) s;


来源:https://stackoverflow.com/questions/38065881/sql-server-2012-sum-over-order-by-gives-error-incorrect-syntax-near-order

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