Sql server 使用分区上的和来计算累积值
我正在运行以下代码来计算累积值Sql server 使用分区上的和来计算累积值,sql-server,Sql Server,我正在运行以下代码来计算累积值 SELECT iid ,item_id ,pg_purch_ind ,SUM_score1 ,SUM(pg_purch_ind) OVER(PARTITION BY item_id ORDER BY SUM_score1 DESC, iid % 100, iid ) AS cum_pg_purch into table2 FROM table1 但它在“order”附近有以下错误语法错误。有人知道问题出在哪里吗?以下是针
SELECT
iid
,item_id
,pg_purch_ind
,SUM_score1
,SUM(pg_purch_ind) OVER(PARTITION BY item_id ORDER BY SUM_score1 DESC, iid % 100, iid ) AS cum_pg_purch
into table2
FROM table1
但它在“order”附近有以下错误语法错误。有人知道问题出在哪里吗?以下是针对较低版本的解决方法
;WITH cte
AS (SELECT iid,
item_id,
pg_purch_ind,
SUM_score1,
Row_number()OVER(partition BY item_id ORDER BY SUM_score1 DESC, iid % 100, iid ) AS rn
FROM Yourtable)
SELECT iid,
item_id,
pg_purch_ind,
SUM_score1,
cum_pg_purch
FROM cte a
CROSS apply (SELECT Sum (pg_purch_ind)
FROM cte b
WHERE a.item_id = b.item_id
AND b.rn <= a.rn) cs (cum_pg_purch)
如果不生成行号,则很难在交叉应用Where子句中处理,因为存在模运算符您无法在低于2012的任何版本中运行此查询,因此您使用的是哪个版本?@Gavin-是,因为您使用的是较旧的Sql Server版本。SQL SERVER 2012中引入了Sumoverorder by