我有下表(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]
但我收到错误消息:
Msg 102,Level 15,State 1,Line 3'order'附近的语法不正确
我之前发布的是粘贴错误的错误消息。遗憾和道歉。你上面看到的是我得到的结果。有人评论说这种语法不正确。现在一切都井然有序,有人能告诉我我做错了吗?
任何人都可以帮助我吗?找不到任何解决方案!谢谢!
答案 0 :(得分:3)
您应该使用ROW_NUMBER
(link)代替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]