2016-10-13 109 views
0

誰能告訴我爲什麼下面不會編譯?SQL SUM通過分區計算%

我試圖計算'M3'標記的事務是整個批次的百分比。

我認爲如果只有一個批次是很容易的,但有時候會有多個。

整個代碼如下:

SELECT 
    [Batch], 
    [DocNum], 
    [Date], 
    [Time], 
    [Location], 
    [ItemCode], 
    [Brand], 
    [Quantity], 
    CASE 
     WHEN [Variance] IS NULL 
      THEN '' 
     ELSE [Variance] 
    END AS [Variance], 
    CASE 
     WHEN [Comments] IS NULL 
      THEN '' 
     ELSE [Comments] 
    END AS [Comments], 
    CASE 
     WHEN [Variance] = 'M3' 
      THEN(
       (
       (SELECT 
        ABS([Quantity]) 
        FROM #BatchReport 
        WHERE [Variance] = 'M3') 
       /
       (SELECT 
        SUM([Quantity]) 
        FROM #BatchReport 
        WHERE [Quantity] > 0) 
       ) * 100) OVER (PARTITION BY [Batch]) 
     ELSE '0' 
    END AS [Pct Loss],       
    SUM([Quantity]) OVER (PARTITION BY [Batch]) AS [Difference], 
    ((SUM([Quantity]) - MAX([Quantity])) * 100)/MAX([Quantity]) OVER (PARTITION BY [Batch]) AS [Pct Difference] 


FROM #BatchReport 
WHERE [DocNum] IS NOT NULL 
GROUP BY [Batch], [DocNum], [Date], [Time], [Variance], [Brand], [Comments], [Quantity], [Location], [ItemCode] 
ORDER BY [Batch], [Date], [Time] 

錯誤文本:

CASE 
     WHEN [Variance] = 'M3' 
      THEN(
       (
       (SELECT 
        ABS([Quantity]) 
        FROM #BatchReport 
        WHERE [Variance] = 'M3') 
       /
       (SELECT 
        SUM([Quantity]) 
        FROM #BatchReport 
        WHERE [Quantity] > 0) 
       ) * 100) OVER (PARTITION BY [Batch]) 
     ELSE '0' 
    END AS [Pct Loss] 

的樣品的東西像什麼我想:Incorrect syntax near the keyword 'OVER'.

如果我刪除這一部分的錯誤消失得到: enter image description here

謝謝!

+1

那麼,你可以發佈錯誤信息以便回答問題 – Lamak

+0

對不起,我修改了問題 – coblenski

回答

2

你的表達邏輯基本上是不可理解的。我猜你想要一些「M3」值和整體值之間的比例。我最好的猜測是:

(100.0 * SUM(CASE WHEN [Variance] = 'M3' THEN ABS([Quantity]) END)/
SUM(CASE WHEN Quantity > 0 THEN Quantity END) OVER (PARTITION BY Batch) 
) as [Pct Loss] 

但是,你GROUP BY是如此複雜,我會感到驚訝,如果您的查詢做你想要什麼。我想你應該在樣本數據和期望的結果上發佈另一個問題。

+0

這一個給出了確切的預期結果。謝謝戈登 – coblenski