Sub topic 5
Creating the table with Power Query
This chapter builds the date table in Power Query with M, the query language behind the Transform Data editor. It assumes you can open Power Query Editor, edit steps in the Advanced Editor, and tell a fact table from a dimension table. It also assumes you have read the earlier chapters on date table requirements and on building the table with DAX. Here you will build the table as a query, add calendar columns, and learn where this approach differs from a DAX calculated table.
Why build the date table in Power Query
A date table must meet the same requirements however you create it. It needs one row per day, no gaps, whole calendar years, unique values, and a column of type Date. Power Query can produce all of that. You can choose it over DAX for these reasons:
- The table is built during refresh, before the model loads. Its columns are ordinary stored columns, not calculated columns that the engine recomputes.
- The query can be copied into a dataflow or another report. Several reports can then share one definition.
- Calendar logic is written next to your other transformations, so a team that maintains queries keeps everything in one place.
| Aspect | Power Query (M) | DAX calculated table |
|---|---|---|
| When it is built | During data refresh | After data loads, when the model is calculated |
| Where it lives | A query that you can reuse or move to a dataflow | Only in the model |
| Source of date bounds | Another query, a parameter, or the current date | Model tables, using functions such as `MIN` and `MAX` |
| Formatting functions | `Date.ToText` with an explicit culture | `FORMAT`, which follows the locale |
| Sort by column | Set later in Model view | Set later in Model view |
Neither option is faster to query. After loading, the engine stores both as the same kind of table.
The minimal query
The smallest useful query generates a list of consecutive dates, converts the list to a table, and sets the column type.
let
StartDate = #date(2020, 1, 1),
EndDate = #date(2026, 12, 31),
Dates = List.Dates(StartDate, Duration.Days(EndDate - StartDate) + 1, #duration(1, 0, 0, 0)),
AsTable = Table.FromList(Dates, Splitter.SplitByNothing(), {"Date"}, null, ExtraValues.Error),
Typed = Table.TransformColumnTypes(AsTable, {{"Date", type date}})
in
TypedEach step does one job:
StartDateandEndDateare literal dates.#date(year, month, day)is the M date constructor.List.Dates(start, count, step)takes three arguments: the first date, how many dates to produce, and the gap between them. Subtracting two dates gives a duration.Duration.Daysturns that duration into a number of days. You add 1 because both the first and the last day belong in the list.#duration(1, 0, 0, 0)is a step of one day. The arguments are days, hours, minutes, and seconds.Table.FromListmakes a one-column table.Splitter.SplitByNothing()tells it to keep each list item whole.{"Date"}names the column.Table.TransformColumnTypessets the column type to Date. Without this step the column has the "any" type, and Power BI will not let you mark the table.
Adding calendar columns in M
Use Table.AddColumn once for each attribute. Its fourth argument sets the column type, so you do not need a separate type-conversion step. This version continues from the Typed step above.
let
StartDate = #date(2020, 1, 1),
EndDate = #date(2026, 12, 31),
Dates = List.Dates(StartDate, Duration.Days(EndDate - StartDate) + 1, #duration(1, 0, 0, 0)),
AsTable = Table.FromList(Dates, Splitter.SplitByNothing(), {"Date"}, null, ExtraValues.Error),
Typed = Table.TransformColumnTypes(AsTable, {{"Date", type date}}),
AddYear = Table.AddColumn(Typed, "Year", each Date.Year([Date]), Int64.Type),
AddQuarterNumber = Table.AddColumn(AddYear, "Quarter Number", each Date.QuarterOfYear([Date]), Int64.Type),
AddQuarter = Table.AddColumn(AddQuarterNumber, "Quarter", each "Q" & Text.From(Date.QuarterOfYear([Date])), type text),
AddMonthNumber = Table.AddColumn(AddQuarter, "Month Number", each Date.Month([Date]), Int64.Type),
AddMonth = Table.AddColumn(AddMonthNumber, "Month", each Date.ToText([Date], "MMM", "en-US"), type text),
AddYearMonth = Table.AddColumn(AddMonth, "Year-Month", each Date.ToText([Date], "yyyy-MM"), type text),
AddWeek = Table.AddColumn(AddYearMonth, "Week Number", each Date.WeekOfYear([Date], Day.Monday), Int64.Type),
AddWeekdayNumber = Table.AddColumn(AddWeek, "Weekday Number", each Date.DayOfWeek([Date], Day.Monday) + 1, Int64.Type),
AddWeekday = Table.AddColumn(AddWeekdayNumber, "Weekday", each Date.ToText([Date], "ddd", "en-US"), type text)
in
AddWeekdayA few details in this query matter:
Date.ToTexttakes an optional culture argument. Passing"en-US"makes the month names the same on every machine and in the Power BI service. Without it, the result can depend on the locale of the machine that runs the refresh.Date.WeekOfYear([Date], Day.Monday)treats Monday as the first day of the week. It counts week 1 as the week containing January 1, so it is not the ISO 8601 week number. If your organization reports ISO weeks, you need extra logic. Check the definition before you rely on this column.Date.DayOfWeekreturns 0 to 6. Adding 1 gives a more readable 1 to 7.- The text columns
Month,Quarter, andWeekdayhave numeric partners. You will use those partners in the sort-by-column chapter, because text sorts alphabetically, so "Apr" comes before "Jan".
Letting the data set the date range
Hard-coded bounds are simple but go stale. When data from 2027 arrives, the table ends too early. Time intelligence measures then return blank for the missing dates. You can derive the bounds from the fact table query instead. This query assumes a query named Sales with an OrderDate column.
let
FirstOrder = Date.From(List.Min(Sales[OrderDate])),
LastOrder = Date.From(List.Max(Sales[OrderDate])),
StartDate = Date.StartOfYear(FirstOrder),
EndDate = Date.EndOfYear(LastOrder),
Dates = List.Dates(StartDate, Duration.Days(EndDate - StartDate) + 1, #duration(1, 0, 0, 0)),
AsTable = Table.FromList(Dates, Splitter.SplitByNothing(), {"Date"}, null, ExtraValues.Error),
Typed = Table.TransformColumnTypes(AsTable, {{"Date", type date}})
in
TypedSales[OrderDate]returns the column as a list.List.MinandList.Maxignore null values.Date.Fromconverts a datetime to a date. This guards against anOrderDatecolumn that includes a time part.Date.StartOfYearandDate.EndOfYearround the range out to whole years. This keeps the table starting on January 1 and ending on December 31.
This approach has costs. The date query now depends on the Sales query. During refresh, Power Query may evaluate Sales more than once, which can slow a large source. It also does not suit DirectQuery sources, where you would not want to scan the fact table for its bounds. For those cases, use fixed bounds or a parameter.
Loading the query
Choose Close and Apply. The query loads as a table named after the query, so rename the query to Date before you apply. Then check the following in Model view and Table view:
- The
Datecolumn shows the calendar icon, which means its type is Date. - The row count equals the number of days in the range. For 2020 to 2026 that is 2,557 rows, because 2020 and 2024 are leap years.
- The first value is January 1 and the last is December 31.
After that, create the relationship from Sales[OrderDate] to 'Date'[Date] and mark the table as the date table. Marking is covered in its own chapter.
Common errors
- The column is typed as Date/Time instead of Date.
Table.TransformColumnTypeswithtype dateprevents this. If you build the list fromDateTimevalues, convert withDate.From. - A "Date" query that fails to load with a type error. A mismatch usually appears when
Sales[OrderDate]contains text. Fix the type in the Sales query first. - A calendar that stops mid-year. This happens when you hard-code the end date or use
List.MaxwithoutDate.EndOfYear. A table that is not a whole year breaks year-to-date totals and the "same period last year" calculation for the last year. - Month names that differ between Desktop and the service. Pass an explicit culture to
Date.ToText. - Refresh errors after renaming the Sales query or column. A data-driven date query depends on those names, so update the references when you rename them.
Exercise
Your date query uses Date.StartOfYear(FirstOrder) and Date.EndOfYear(LastOrder) for its bounds. The earliest order is 14 March 2021 and the latest is 9 October 2025. What are the first and last dates in the table, and how many rows does it have?
Show answer
The first date is 1 January 2021 and the last is 31 December 2025. That is five whole years: 365 + 365 + 365 + 366 + 365 = 1,826 rows, because 2024 is the only leap year in the range. Using Date.From on the minimum and maximum values makes sure the bounds are dates, not datetimes.
Exercise
A colleague adds a Month column with Date.ToText([Date], "MMM") and later reports that the labels come out in a different language in the Power BI service. What is the cause, and what is the fix?
Show answer
Without a culture argument, Date.ToText uses the locale of the environment that runs the query, which can differ between Desktop and the service. Pass an explicit culture, for example Date.ToText([Date], "MMM", "en-US"), so the output is the same everywhere.