将x个工作日添加到自定义列中的日期

时间:2017-02-07 20:45:51

标签: excel excel-formula excel-2013 powerquery m

我尝试在Power Query中添加自定义列,如果符合条件,则会增加3个工作日,否则会增加2个工作日。

我可以有条件地添加没有问题的天数,但是在添加工作日时遇到了麻烦。我知道这可以使用=IF X = 1,WORKDAY([REFERENCE],3),WORKDAY([REFERENCE],2)在excel中轻松完成,但是如何在查询编辑器中执行与自定义列相同的操作?

以下是我所拥有的,包括周末的日子:

=if [REF]="1" then Date.AddDays([ETA],3) else Date.AddDays([ETA],2)

3 个答案:

答案 0 :(得分:1)

解决方案是将其分解为两个组成部分:

  1. 根据您的初始条件,添加2或3天
  2. 如果周六或周日结束,请再增加2天以跳过周末
  3. 您已经实施了第1步。

    您现在只需要执行第2步,如果需要,可以再添加2天。您可以使用DayOfWeek功能来确定您的起点,以确定您是否需要额外的2天:

    如果您要增加3个工作日,那么如果首天是周三,周四或周五,您还需要再增加2天:

    if Date.DayOfWeek([ETA], Day.Wednesday) <= 2 then {Add 2 more days}
    

    如果您要增加2个工作日,那么如果首日是周四或周五,则需要再增加2天:

    if Date.DayOfWeek([ETA], Day.Thursday) <= 1 then {Add 2 more days}
    

    您可以将这些内容合并到您的初始陈述中。

答案 1 :(得分:1)

我写了一个解决这个问题的自定义函数,除非你需要考虑假期。它有点普遍,它适用于2或200或2000天。在Excel中等于=WORKDAY(date;days)函数。

这是:

(startDate, days) =>
    let
        Step1 = List.Dates(Date.AddDays(startDate, 1), days + Number.RoundUp(days/7*3+4,0), #duration(1,0,0,0)), //provision list of added days with 3 more days per each added week, starting from startDate + 1 day
        Step2 = List.Select(Step1, (item) => Date.DayOfWeek(item, Day.Monday) < 5), // select only workdays
        Step3 = List.FirstN(Step2, days), //select required number of workdays
        Output = if days <= 0 then startDate else List.Last(Step3)
    in
        Output

您可以将其另存为查询,将其命名为AddWorkdays,并按此使用:

YourStepName = Table.AddColumn(yourTable, "CustomColumnName", 
                    each AddWorkdays([ETA], if [REF]="1" then 3 else 2) 
                   //note that [REF]="1" filters a text value, not number!

否则,您可以在代码中插入此函数

fnAddWorkdays = (startDate, days) =>
let
    Step1 = List.Dates(Date.AddDays(startDate, 1), days + Number.RoundUp(days/7*3+4,0), #duration(1,0,0,0)), //provision list of added days with 3 more days per each added week, starting from startDate + 1 day
    Step2 = List.Select(Step1, (item) => Date.DayOfWeek(item, Day.Monday) < 5), // select only workdays
    Step3 = List.FirstN(Step2, days), //select required number of workdays
    Output = if days <= 0 then startDate else List.Last(Step3)
in
    Output,

答案 2 :(得分:0)

对 Eugene 的响应略有改进,允许减少工作日。

= (startDate, days) =>
let
    Step1 = if days >= 0 then List.Dates(Date.AddDays(startDate, 1), days + Number.RoundUp(days/7*3+4,0), #duration(1,0,0,0)) 
            else List.Dates(Date.AddDays(startDate, -1), -days + Number.RoundUp(-days/7*3+4,0), #duration(-1,0,0,0)), //provision list of added days with 3 more days per each added week, starting from startDate + 1 day
    Step2 = List.Select(Step1, (item) => Date.DayOfWeek(item, Day.Monday) < 5), // select only workdays
    Step3 = List.FirstN(Step2, Number.Abs(days)), //select required number of workdays
    Output = List.Last(Step3)
in
    Output

只需为 days 输入一个负值。