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
抛出错误:
Incorrect syntax near 'order'.
https://msdn.microsoft.com/en-us/library/ms187810.aspx
SQL Server 2012 不支持 sum over order by 吗?如果我删除 order by 并仅使用 partition by 它有效但对于“C”我得到所有行的 60。我想要运行总计。
更多信息:
- Microsoft SQL Server 管理工作室 11.0.2100.60
- Microsoft Analysis Services 客户端工具 11.0.2100.60
- Microsoft 数据访问组件 (MDAC) 6.1.7601.17514
数据库选项->兼容级别只显示2000、2005和2008,选择2008。
努力奔跑
ALTER DATABASE database_name
SET COMPATIBILITY_LEVEL = 110
抛出错误:
Valid values of the database compatibility level are 80, 90, or 100.
最佳答案
直到 SQL Server 2012+ 才支持累积和。据推测,您正在使用 SQL Server 2005 或 2008,或者您的兼容性设置设置为 105 或更低(请参阅 here)。
在这些版本中,您可以使用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;
关于SQL 服务器 2012 : sum over order by gives error Incorrect syntax near 'order' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38065881/