How to create Date table using M query - CloudFronts

How to create Date table using M query

Posted On December 13, 2021 by Yogesh Gunjal Posted in  Tagged in ,

You Might have seen the other ways to create the DateTable in Power BI using m query by adding two Custom columns such as startdate and enddate and then using DateRange function you can populate the dates between startdate and enddate

However, in this blog, we will see the M query that enables you to create the datetable on user define the start and end date using parameters

Step 1: Open the Power BI desktop application and then select the option Transform Data

Step2: Click on the new source. then select the Blank query option from the dropdown

Step3: Click on Advanced editor and paste the below query


(StartDate as date, EndDate as date)=>
let
    //Capture the date range from the parameters
    StartDate = #date(Date.Year(StartDate), Date.Month(StartDate), 
    Date.Day(StartDate)),
    EndDate = #date(Date.Year(EndDate), Date.Month(EndDate), 
    Date.Day(EndDate)),
    //Get the number of dates that will be required for the table
    GetDateCount = Duration.Days(EndDate - StartDate),
    //Take the count of dates and turn it into a list of dates
    GetDateList = List.Dates(StartDate, GetDateCount, 
    #duration(1,0,0,0)),
    //Convert the list into a table
    DateListToTable = Table.FromList(GetDateList, 
    Splitter.SplitByNothing(), {"Date"}, null, ExtraValues.Error),
    //Create various date attributes from the date column
    //Add Year Column
    YearNumber = Table.AddColumn(DateListToTable, "Year", 
    each Date.Year([Date])),
    //Add Quarter Column
    QuarterNumber = Table.AddColumn(YearNumber , "Quarter", 
    each "Q" & Number.ToText(Date.QuarterOfYear([Date]))),
    //Add Week Number Column
    WeekNumber= Table.AddColumn(QuarterNumber , "Week Number", 
    each Date.WeekOfYear([Date])),
    //Add Month Number Column
    MonthNumber = Table.AddColumn(WeekNumber, "Month Number", 
    each Date.Month([Date])),
    //Add Month Name Column
    MonthName = Table.AddColumn(MonthNumber , "Month", 
    each Date.ToText([Date],"MMMM")),
    //Add Day of Week Column
    DayOfWeek = Table.AddColumn(MonthName , "Day of Week", 
    each Date.ToText([Date],"dddd"))
in
    DayOfWeek

Step 4: After clicking on ok you will see the input fields to enter the start and end date

Step 5: Enter the dates required and then click on Invoke

You can see the new table is create for given date range

Hope this helps you!! Thank You


Share Story :