简体   繁体   English

SQL Server 2008 R2语法错误

[英]SQL Server 2008 R2 syntax error

Could somebody please tell me why this is causing a syntax error in SQL Server 2008 R2? 有人可以告诉我为什么这会导致SQL Server 2008 R2出现语法错误吗? It works fine in SQL Server 2014. 它在SQL Server 2014中正常运行。

SELECT        
    CustomerId, RequestDate, 
    SUM(InitialActualCount + (KeyCardCount * x.Activity)) 
       OVER (PARTITION BY CustomerId  ORDER BY RowNumber) AS TotalActualCount,
    RowNumber
FROM            
    (SELECT        
        *, 
        ROW_NUMBER() OVER (PARTITION BY CustomerId
                      ORDER BY CustomerID, RequestDate) AS RowNumber
     FROM            
        RequestTable) x

Table structure: 表结构:

 RequestTable (CustomerId, RequestDate,  KeyCardCount, Activity, InitialActualCount)        

Error: 错误:

Incorrect syntax near 'order'. 'order'附近的语法不正确。
Incorrect syntax near 'x'. 'x'附近的语法不正确。

Thank you in advance for any help! 预先感谢您的任何帮助!

At least one of your issues is this line: 您的问题中至少有一个是此行:

SELECT /*snip*/ sum(InitialActualCount + (KeyCardCount * x.Activity))
  OVER (partition BY CustomerId  ORDER BY RowNumber) AS TotalActualCount /*snip*/

The ability to add an ORDER BY clause in an OVER clause with an aggregate ( SUM in you case) was added in SQL Server 2012. SQL Server 2012中增加了在具有聚合的OVER子句中添加ORDER BY子句的能力(在您的情况下为SUM )。

Getting running totals was a well known problem before 2012 - see Best approaches for running totals – updated for SQL Server 2012 for an exhaustive discussion of this. 获取运行总计是2012年之前的一个众所周知的问题-有关此问题的详尽讨论,请参见SQL Server 2012的最佳运行总计方法-已更新

SELECT        
   *, 
   ROW_NUMBER() OVER (PARTITION BY CustomerId
                      ORDER BY CustomerID, RequestDate) AS RowNumber
FROM RequestTable

Don't you need an alias for using * ? 使用*不需要别名吗?

SELECT        
   a.*, 
   ROW_NUMBER() OVER (PARTITION BY CustomerId
                      ORDER BY CustomerID, RequestDate) AS RowNumber
FROM RequestTable a

Lose the "x" as per: 按照以下方式丢失“ x”:

 SELECT
  CustomerId,
  RequestDate,
  SUM(InitialActualCount + ( KeyCardCount * x.Activity )) OVER ( PARTITION BY CustomerId ORDER BY RowNumber ) AS TotalActualCount,
  RowNumber
 FROM
  (
    SELECT
      *,
      ROW_NUMBER() OVER ( PARTITION BY CustomerId ORDER BY CustomerID, RequestDate ) AS RowNumber
    FROM
      RequestTable
  ) RequestTable ( CustomerId, RequestDate, KeyCardCount, Activity,
                   InitialActualCount )     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM