2016-12-07 42 views
1

我運行下面的代碼來計算累計值使用求和分區計算

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 

累計值,但它具有以下錯誤「附近有語法錯誤‘秩序’。」有誰知道這是什麼問題?

+2

你不能在任何版本上運行此查詢的Where條款較少比2012那麼你正在使用哪個版本? –

回答

1

這裏是一個較小的版本

;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) 

不會產生Row_Number的解決方法是相當困難的交叉處理適用,因爲模運算

+0

你知道我爲什麼收到錯誤信息嗎? – Gavin

+0

@Gavin - 是的,因爲您使用的是舊版SQL Server版本。在SQL SERVER 2012中引入了'sum()over(order by)' –