T SQL CTE上一行计算

时间:2019-06-13 15:56:33

标签: sql sql-server common-table-expression

我正在使用SQL Server2016。

我有下表:

SKU     Shop       Week    ShopPrioirty    Replen      Open_Stk  Open_Stk Calc
111     100         1            1           0           17         NULL
111     200         1            2           2           NULL       NULL 
111     300         1            3           0           NULL       NULL
111     400         1            4           0           NULL       NULL

222     100         2            1           5          17          NULL 
222     200         2            2           5          NULL        NULL
222     300         2            3           5          NULL        NULL
222     400         2            4           5          NULL        NULL

这是期望的结果:

SKU     Shop      Week    ShopPrioirty    Replen      Open_Stk  Open_Stk Calc
111     100         1            1           0           17         17
111     200         1            2           2          NULL        17
111     300         1            3           0          NULL        15
111     400         1            4           0          NULL        15

222     100         2            1           20           17        17
222     200         2            2           15          NULL       12
222     300         2            3           12          NULL        7
222     400         2            4           10          NULL        2

我需要根据上一行更新“ Open_Stk Calc”:

'Open_Stk Calc' - IIF('Replen'<=IIF('Open_Stk'>=0,'Open_Stk',0),'Replen',0)

我正在使用CTE根据先前行的计算来更新行。这是我的SQL:

    ;WITH CTE AS 
    (
        SELECT
        SKU,
        [Shop],
        [Week],
        [Store_Priority],
        [Replen],      
        [Open_Stk],
        [Open_Stk Calc],
        FIRST_VALUE([Open_Stk]) OVER ( PARTITION BY [SKU] ,[Week] ORDER BY [Store_Priority] ROWS UNBOUNDED PRECEDING) 
        - 
ISNULL(SUM(IIF([Replen] <= IIF([Open_Stk]>=0,[Open_Stk],0),[Replen],0))
        OVER (PARTITION BY [SKU] ,[Week] ORDER BY [Store_Priority] ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) AS CurrentStock
    FROM [tblTEST])

    UPDATE CTE 
    SET [Open_Stk Calc] = CurrentStock

但是,这将产生以下结果:

SKU     Shop       Week    ShopPrioirty    Replen      Open_Stk  Open_Stk Calc
111     100         1            1           0           17         17
111     200         1            2           2           NULL       17 
111     300         1            3           0           NULL       17
111     400         1            4           0           NULL       17

这不是理想的结果-我哪里出错了?

1 个答案:

答案 0 :(得分:1)

MS documentation中可以看到,OVER子句支持特定类型的功能:

Ranking functions 
Aggregate functions 
Analytic functions 
NEXT VALUE FOR function

正如Luis Cazares在其评论中指出的那样,它们都不包含IIF

您的代码表明您关于您正在做的事情的线索-也许您忘记将IIF放在SUM内了?