问题
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