来自Microsoft SQL Server 2012 T-SQL的示例查询基本不起作用

时间:2016-04-04 06:53:01

标签: sql-server tsql sql-server-2012 sql-server-2008-r2 window-functions

我最近开始关注Microsoft SQL Server 2012 T-SQL基础教程以学习T-SQL。我尝试在SQL Server 2008 r2中执行以下查询

SELECT empid, ordermonth, val,
SUM(val) OVER(PARTITION BY empid
              ORDER BY ordermonth
              ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS runval
FROM Sales.EmpOrders;

查询无法执行,并显示以下错误消息

Msg 102, Level 15, State 1, Line 5
Incorrect syntax near 'ROWS'.

这是sales.emporders视图的片段

empid   ordermonth                  qty     val         numorders
-----------------------------------------------------------------
5       2007-10-01 00:00:00.000     361     7581.33         9
6       2007-06-01 00:00:00.000     173     3464.81         7
9       2007-09-01 00:00:00.000     93      8776.15         5
5       2008-02-01 00:00:00.000     276     5377.06         15
5       2007-07-01 00:00:00.000     213     6475.40         5
4       2006-10-01 00:00:00.000     613     13718.97        27

需要帮助找出解决sql server 2008 r2的方法

3 个答案:

答案 0 :(得分:1)

它没有SQL Server 2012功能。您可以使用功能OVER,但在2008R2中没有任何功能:ROWS BETWEEN UNBOUNDED PRECEDING

请参阅:

https://msdn.microsoft.com/en-us/library/ms189461(v=sql.105).aspx(2008R2)

AND

https://msdn.microsoft.com/en-us/library/ms189461(v=sql.110).aspx(2012)

答案 1 :(得分:0)

SELECT empid, 
       ordermonth, 
       val,
       (SELECT SUM(val) 
        FROM Sales.EmpOrders ee 
        WHERE e.empid=ee.empid 
        AND ee.ordermonth<=e.ordermonth) AS runval
FROM Sales.EmpOrders e;

答案 2 :(得分:0)

If you are using UNBOUNDED PRECEDING I think you can just drop it
Did you try?

SELECT empid, ordermonth, val
     , SUM(val) OVER(PARTITION BY empid ORDER BY ordermonth) AS runval
FROM Sales.EmpOrders;