8

我有下表(SQL Server 2012):

DID - cust id
GID - order id
AMT - order amt
Gf_Date - order date
SC - order reversal amount

我正在尝试计算订单的运行计数和客户的运行总销售额,以便我可以将标志分配给客户累计销售额达到 1,000 美元的时间点。作为第一步,我运行了这个查询:

Select
  [DID]
, [AMT]
, [Gf_Date]
, COUNT([GID]) OVER (PARTITION BY [DID] ORDER BY [Gf_Date]) [RunningGift_Count]
, SUM([AMT]) OVER (PARTITION BY [DID] ORDER BY [Gf_Date]) [CumlativeTotal]
FROM [dbo].[MCT]
WHERE [SC] is null
ORDER BY [DID]

但我收到错误消息:

消息 102,级别 15,状态 1,第 3 行 'order' 附近的语法不正确

我早些时候发布了这个并粘贴了错误的错误消息。遗憾和道歉。你在上面看到的是我得到的结果。有人评论说这种语法不正确。现在一切都井井有条,有人可以告诉我我做错了什么吗?

谁能帮我吗?在任何地方都找不到解决方案!谢谢!

4

1 回答 1

7

您应该使用ROW_NUMBER(链接) 而不是COUNT

DECLARE @Threshold NUMERIC(19,2)=1000; -- Use the same data type as `[AMT]`'s data type

Select
  [DID]
, [AMT]
, [Gf_Date]
--, COUNT([GID]) OVER (PARTITION BY [DID] ORDER BY [Gf_Date]) [RunningGift_Count]
, ROW_NUMBER() OVER (PARTITION BY [DID] ORDER BY [Gf_Date]) [RunningGift_Count]
, SUM([AMT]) OVER (PARTITION BY [DID] ORDER BY [Gf_Date]) [CumlativeTotal]
, CASE
      WHEN SUM([AMT]) OVER (PARTITION BY [DID] ORDER BY [Gf_Date]) >= @Threshold THEN 1
      ELSE 0
  END IsThresholdPassed
FROM [dbo].[MCT]
WHERE [SC] is null
ORDER BY [DID]
于 2013-07-27T05:54:14.780 回答