如何使用Power Query M语言编写WorkdayDiff日期函数

时间:2019-04-01 08:06:41

标签: powerbi powerquery powerbi-desktop m

我正在尝试创建一个自定义函数,该函数计算两个日期之间的工作日差。我在SSRS中完成了相同的功能:

Public Function WorkdayDiff(StartDate As Date, EndDate As Date) As Date

  Return Datediff("ww", StartDate, EndDate, vbMonday) + 
         Datediff("ww", StartDate, EndDate, vbTuesday) + 
         Datediff("ww", StartDate, EndDate, vbWednesday) + 
         Datediff("ww", StartDate, EndDate, vbThursday) + 
         Datediff("ww", StartDate, EndDate, vbFriday)

End Function

我现在尝试使用Power Query M语言做同样的事情,但是这让我一直说:

  

类型未定义。

这是我在Power BI的高级编辑器中的代码:

(DateStart as Date, DateEnd as Date) as Date =>

let
    WorkdayDiff = Datediff("ww",DateStart ,DateEnd, vbMonday) +
                Datediff("ww",DateStart ,DateEnd, vbTuesday) + 
                Datediff("ww",DateStart ,DateEnd, vbWednesday) + 
                Datediff("ww",DateStart ,DateEnd, vbThursday) + 
                Datediff("ww",DateStart ,DateEnd, vbFriday)
in
    WorkdayDiff

1 个答案:

答案 0 :(得分:1)

您的代码有几个问题。

得到Type not defined的原因是M区分大小写,并且在引用数据类型时需要使用date而不是Date。 M也没有Datediff函数,也不了解vbMonday的含义。您必须使用M函数,而不仅仅是粘贴SSRS代码并希望它起作用。

这是this post风格的M中的可能实现。

let
    WorkdayDiff = (StartDate as date, EndDate as date) as number =>
    let
        DateList = List.Dates(StartDate, Number.From(EndDate - StartDate) + 1, #duration(1,0,0,0)),
        RemoveWeekends = List.Select(DateList, each Date.DayOfWeek(_, Day.Monday) < 5),
        CountDays = List.Count(RemoveWeekends)
    in
        CountDays
in
    WorkdayDiff