插入一列以计算与新日期相关的值之间的差异

时间:2019-01-29 00:06:37

标签: excel powerpivot powerquery

我正在使用超级查询创建一个表,该表中有#个部分和数量。每周电源查询都会刷新,以获取部分#的新的每周数量。我正在尝试创建一个列,该列计算每周更改的数量的差异(增加或减少)。

我的3列是: 日期, 产品编号, 数量

enter image description here

我似乎找不到用于Value.Subtract([QTY],[QTY],[Date] [产品编号])的正确语法

1 个答案:

答案 0 :(得分:0)

您可以使用M(高级查询语言)进行此操作:

#"Sorted Rows" = Table.Sort(#"Prior Step",{{"Product Number", Order.Ascending}, {"Date", Order.Ascending}}),
#"Added Index" = Table.AddIndexColumn(#"Sorted Rows", "Index", 0, 1),
#"Added Qty Change" = Table.AddColumn(#"Added Index", "Qty Change", each try if #"Added Index"[Product Number]{[Index]-1} = [Product Number] then [Qty] - #"Added Index"[Qty]{[Index]-1} else null otherwise null, type number),
#"Removed Columns" = Table.RemoveColumns(#"Added Qty Change",{"Index"})

不过,我认为在数据模型中使用DAX进行处理会更有效。 将表加载到数据模型,然后添加“计算列”:

Qty Change:= 

VAR CurrentDate =  'Inventory Balance'[Date]

VAR CurrentProduct = 'Inventory Balance'[Product Number]

VAR PreviousDate = 
    CALCULATE ( 
        MAX ( 'Inventory Balance'[Date] ),
        FILTER ( 
            ALL ( 'Inventory Balance' ),
            'Inventory Balance'[Date] < CurrentDate
            && 'Inventory Balance'[Product Number] = CurrentProduct
        )
    )

VAR PreviousQty = 
    CALCULATE ( 
        SUM ( 'Inventory Balance'[Qty] ),
        FILTER ( 
            ALL ( 'Inventory Balance' ),
            'Inventory Balance'[Date]  =  PreviousDate
            && 'Inventory Balance'[Product Number] = CurrentProduct
        )
    )

RETURN
    'Inventory Balance'[Qty] - PreviousQty