Sub topic 2
Creating a Date Table with Power Query
Assume you know Power BI Desktop, basic Power Query, and relationships between fact and dimension tables. A date table is a continuous table with one row for each calendar date. It lets reports filter sales consistently and supports time-based calculations.
Creating the table with Power Query
In Power BI, select Home > Transform data, then open New Source > Blank Query. Open Advanced Editor and replace the query with this code:
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([Quarter Number]),
type text
),
AddMonthNumber = Table.AddColumn(
AddQuarter,
"Month Number",
each Date.Month([Date]),
Int64.Type
),
AddMonth = Table.AddColumn(
AddMonthNumber,
"Month",
each Date.MonthName([Date]),
type text
),
AddWeek = Table.AddColumn(
AddMonth,
"Week Number",
each Date.WeekOfYear([Date]),
Int64.Type
)
in
AddWeekThe query creates every date in the range, including dates with no sales. Change StartDate and EndDate to cover the full reporting period.
Adding and sorting calendar columns
Use numeric columns for sorting and text columns for display.
| Display column | Sort by column |
|---|---|
| Month | Month Number |
| Quarter | Quarter Number |
| Year-Month | Year-Month Number |
After loading the query, select the Month column in Table view. Choose Column tools > Sort by column > Month Number. Otherwise, month names sort alphabetically, such as April, August, and December.
Relating the date table to the fact table
In Model view, create a one-to-many relationship:
Date[Date]is the one side.Sales[OrderDate]is the many side.- Filter direction is usually single direction from
DatetoSales.
A common error is connecting a date table to a Date/Time fact column when the times differ. Create a date-only column in the fact table before creating the relationship.
Exercise
Why should Month be sorted by Month Number?
Show answer
Month names sort alphabetically by default, so Month Number restores calendar order from January through December.