SQL SUM OVER PARTITION BY计算组的百分比

时间:2016-10-13 14:39:31

标签: sql window-functions sql-server-2016

谁能告诉我为什么以下不会编译?

我正在尝试计算整个批次中'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]

错误文字:Incorrect syntax near the keyword 'OVER'.

如果删除此部分,错误就会消失:

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]

我想要得到的东西样本: enter image description here

谢谢!

1 个答案:

答案 0 :(得分: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非常复杂,如果您的查询符合您的要求,我会感到惊讶。我想你应该发布另一个包含样本数据和预期结果的问题。