Introduction
For years, I’ve constructed date tables in a tabular mannequin with DAX code, when there was no different supply for such a desk.
I created a template code and reused it time and again. It really works very effectively in a mess of conditions.
I distributed it to my purchasers, and they’re all proud of it.
However about two weeks in the past, I had a dialogue with a colleague that opened my eyes to a strategy to do it, which I didn’t take into consideration till now.
So, let’s have a look at the variants to construct a date desk and examine them.
However regardless of how one can do it, it’s essential to know the necessities for date tables in semantic fashions.
What occurs when there’s a DWH?
First, when I’ve an information retailer and a supply for the semantic mannequin, whether or not a relational database, a Cloth Lake, or another centralised information retailer, I’ll construct it there and eat it within the Semantic mannequin.
The choices obtainable there for constructing such a desk are very in depth and versatile, and neither DAX nor Energy Question is extra environment friendly.
Subsequently, there isn’t any query about how one can do it in such a case.
DAX tables
Producing a date desk in DAX is comparatively simple and simple.
DAX affords a large number of capabilities so as to add columns and options to a date desk.
You all the time begin with the CALENDAR() name to set the beginning and finish date.
You possibly can both use mounted values, like MIN()/MAX() calls, based mostly on obtainable information to get start- and end-date from an information desk inside the information mannequin, or some (Energy Question) parameters.
For instance, one thing like this:
DimDate =
CALENDAR (
DATE ( YEAR (
MIN ( 'On-line Gross sales Order'[Date] )
), 1, 1 ),
DATE ( YEAR (
MAX ( 'On-line Gross sales Order'[Date] )
), 12, 31 )
)
As Microsoft requires having full years within the date desk, I begin with the primary of January and finish with the final of December (31.12.).
Subsequent, you’ll be able to add additional columns so as to add the years, quarters, months and days to the desk.
You are able to do it inside the definition of the desk through the use of ADDCOLUMNS():
DimDate =
ADDCOLUMNS (
CALENDAR (
DATE ( YEAR ( MIN ( 'On-line Gross sales Order'[Date] ) ), 1, 1 ),
DATE ( YEAR ( MAX ( 'On-line Gross sales Order'[Date] ) ), 12, 31 )
),
"Date_ID", FORMAT ( [Date], "YYYYMMDD" ),
"12 months", YEAR ( [Date] ),
"Monthnumber", FORMAT ( [Date], "MM" ),
"YearMonth_ID", CONVERT ( FORMAT ( [Date], "YYYYMM" ), INTEGER ),
"YearMonth", FORMAT ( [Date], "YYYY/MM" ),
"YearMonthShort", FORMAT ( [Date], "YYYY/mmm" ),
"MonthNameShort", FORMAT ( [Date], "mmm" ),
"MonthNameLong", FORMAT ( [Date], "mmmm" ),
"MonthDate", EOMONTH ( [Date], 0 ),
// Person Format String mmm yyyy (Brief Month) or mmmm yyyy (Lengthy Month),
"DayOfWeekNumber", WEEKDAY ( [Date], 2 ),
"DayOfWeek", FORMAT ( [Date], "dddd" ),
"DayOfWeekShort", FORMAT ( [Date], "ddd" ),
"IsWorkday", IF ( WEEKDAY ( [Date] ) IN { 1, 7 }, 0, 1 ),
"SemesterNumber", IF ( INT ( FORMAT ( [Date], "MM" ) ) <= 6, 1, 2 ),
"Semester", IF ( INT ( FORMAT ( [Date], "MM" ) ) <= 6, "S1", "S2" ),
"YearSemesterNumber",
IF (
INT ( FORMAT ( [Date], "MM" ) ) <= 6,
YEAR ( [Date] ) * 10 + 1,
YEAR ( [Date] ) * 10 + 2
),
"YearSemester",
IF (
INT ( FORMAT ( [Date], "MM" ) ) <= 6,
FORMAT ( [Date], "YYYY" ) & "/S1",
FORMAT ( [Date], "YYYY" ) & "/S2"
),
"QuarterNumber", INT ( FORMAT ( [Date], "q" ) ),
"Quarter", "Q" & FORMAT ( [Date], "Q" ),
"YearQuarterNumber",
YEAR ( [Date] ) * 10 + FORMAT ( [Date], "Q" ),
"YearQuarter",
FORMAT ( [Date], "YYYY" ) & "/Q" & FORMAT ( [Date], "Q" ),
"DayOfMonth", FORMAT ( [Date], "DD" ),
"DayOfYear", DATEDIFF ( DATE ( YEAR ( [Date] ), 1, 1 ), [Date], DAY ) + 1,
"DayOfYear_woWeekend", NETWORKDAYS ( DATE ( YEAR ( [Date] ), 1, 1 ), [Date], 1 ),
"RestDaysInYear",
DATEDIFF (
DATE ( YEAR ( [Date] ), 1, 1 ),
DATE ( YEAR ( [Date] ), 12, 31 ),
DAY
)
- DATEDIFF ( DATE ( YEAR ( [Date] ), 1, 1 ), [Date], DAY ) + 1,
"RestDaysInYear_woWeekend",
NETWORKDAYS (
DATE ( YEAR ( [Date] ), 1, 1 ),
DATE ( YEAR ( [Date] ), 12, 31 ),
1
)
- NETWORKDAYS ( DATE ( YEAR ( [Date] ), 1, 1 ), [Date], 1 ),
"WeekNumber", WEEKNUM ( [Date], 21 )
)
The attention-grabbing half is that it’s potential to move the title or a locale setting to the FORMAT() operate, for instance, to create month names in numerous languages:
DimDate =
ADDCOLUMNS(
CALENDAR(DATE(YEAR(MIN('On-line Gross sales Order'[Date])), 1, 1)
,DATE(YEAR(MAX('On-line Gross sales Order'[Date])), 12, 31)
),
"Date_ID", FORMAT ( [Date], "YYYYMMDD" ),
"12 months", YEAR ( [Date] ),
"Monthnumber", FORMAT ( [Date], "MM" ),
"YearMonth_ID", CONVERT(FORMAT ( [Date], "YYYYMM" ), INTEGER),
"YearMonth", FORMAT ( [Date], "YYYY/MM" ),
"MonthNameShort", FORMAT ( [Date], "mmm" ),
"MonthNameShort_DE", FORMAT ( [Date], "mmm", "de-de" ),
"MonthNameLong", FORMAT ( [Date], "mmmm" ),
"MonthNameLong_DE", FORMAT ( [Date], "mmmm", "de-de" ),
"DayOfWeekNumber", WEEKDAY ( [Date], 2 ),
"DayOfWeek", FORMAT ( [Date], "dddd" ),
"DayOfWeek_DE", FORMAT ( [Date], "dddd", "de-de" ),
"DayOfWeekShort", FORMAT ( [Date], "ddd" ),
"DayOfWeekShort_DE", FORMAT ( [Date], "ddd", "de-de" )
)
This ends in a desk like this:

Notice the third parameter “de-de” of the FORMAT() name and the corresponding columns within the desk—one in English and one in German.
However with the appearance of user-context-aware calculated columns, this may also be applied in another way.
Learn right here for extra details about this new characteristic.
In case you want to calculate columns with a extra advanced logic, you are able to do it with calculated columns utilizing Context transition to entry all the desk.
If you happen to don’t know context transition, learn this piece with an evidence of this idea:
One instance of that is calculating the week quantity for Fiscal Years after they don’t align with calendar years.
Doing this with a mathematical components is a nightmare, or my math expertise aren’t subtle sufficient.
Energy Question and Information Flows
Now we come to the final variant: Utilizing Energy Question or Information Flows.
To start with, I don’t distinguish between Energy Question and Information Flows in v1 or v2, as all of them function on the identical rules and use the identical language.
I begin constructing the date desk in Energy Question by creating three parameters:
- StartYear: The primary 12 months within the date desk
- YearsToLoad: What number of years must be coated by the date desk
- FirstMonthOfFiscalYear: Which is the primary Month of the Fiscal 12 months.
If the Fiscal 12 months aligns with the Calendar 12 months, this can be 1; in any other case, it will likely be the variety of the primary month of the Fiscal 12 months.
All additional code will depend on these parameters.
The beginning is all the time with the identical command: Listing.Dates()
The parameters of this operate are:
- The Beginning date
- The variety of days to create the record
- The interval, which on this context is days
This results in a line like this, whereas utilizing the parameters talked about above:
Listing.Dates(#date(StartYear,1,1),366 * YearsToLoad,#period(1,0,0,0))
And right here comes the primary impediment:
Normally, we’d like a date desk which spans a number of years. However each fourth 12 months is a bissextile year.
So, how can we do that, as Microsoft requires a date desk that spans total years?
The answer is to get the final date of the final 12 months (31. December) and filter the rows to maintain solely these earlier than or equal to this date.
And that is the explanation why I multiply three hundred and sixty six days by the parameter YearsToLoad.
Right here is the complete M-Code for this state of affairs:
let
Supply = Listing.Dates(#date(StartYear,1,1),366 * YearsToLoad,#period(1,0,0,0)),
#"Transformed to Desk" = Desk.FromList(Supply, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
#"Renamed Columns" = Desk.RenameColumns(#"Transformed to Desk",{{"Column1", "Date"}}),
#"Modified Sort" = Desk.TransformColumnTypes(#"Renamed Columns",{{"Date", sort date}}),
#"Added Final Legitimate Date" = Desk.AddColumn(#"Modified Sort", "Final Legitimate Date", every #date(Date.12 months(Listing.Max(#"Modified Sort"[Date])) - 1, 12, 31), sort date),
#"Preserve solely legitimate dates" = Desk.SelectRows(#"Added Final Legitimate Date", every [Date] <= [Last Valid Date])
in
#"Preserve solely legitimate dates"
Subsequent, I can begin including all columns wanted to construct a whole date desk.
First, I add a Date_ID, with a numerical illustration of the date:
Date.12 months([Date]) * 10000 ) + (Date.Month([Date]) * 100) + Date.Day([Date])
This column should be set to an integer information sort. Subsequently, all the line of M-Code is that this:
Desk.AddColumn(#"Preserve solely legitimate dates", "Date_ID", every ( Date.12 months([Date]) * 10000 ) + (Date.Month([Date]) * 100) + Date.Day([Date]), Int64.Sort)
Notice the expression Int64.Sort earlier than the final closing bracket. This units the information sort in the identical command, eliminating the necessity for a further step.
Subsequent, I can use the obtainable prospects within the Energy Question Editor so as to add further columns that I generally add to my date tables:

As you’ll be able to see, we will add a lot of columns with out writing code.
However sooner or later, we should write our personal code so as to add further columns—for instance, columns to retailer the 12 months and the corresponding interval.
Listed below are a few of these columns:
- 12 months/Month Title
- 12 months/Quarter
- 12 months/Week
Then, for the columns for the beginning and finish date for any interval, like every week or a month.
I take advantage of these columns for {custom} time intelligence code in DAX. I wrote another items right here on this matter, corresponding to weekly calculations.
And sooner or later, the same old M-Code is inadequate to acquire the required data.
For instance, once I have to get a week-aligned 12 months column (YearForWeek).
For these situations, I began writing {custom} M-functions that enable me to entry a date vary for every row, which is in any other case unattainable in M.
On this case, I added this operate:
(DateInput as date) as quantity =>
let
ClosestThursday = Date.AddDays(DateInput, -1 * Date.DayOfWeek(DateInput, Day.Monday) + 3),
12 months = Date.12 months(ClosestThursday)
in
12 months
If you happen to’re not acquainted with {custom} M-functions, I strongly advocate this nice characteristic.
I’ll add some hyperlinks within the References part under.
After all the growth of the date desk, I bought these {custom} capabilities:
- GetISOYear
Get the weekly aligned 12 months - GetISOWeek
Calculate the proper week quantity based mostly on the ISO Normal - CalculateMonthDiff
The distinction in months between two dates - CalculateQuarterDiff
The distinction in quarters between two dates - GetFiscalWeekNumber
Calculate the week-number beginning with the week of the day on which the Fiscal 12 months begins. - GetCurrentFiscalYear
This will get the present Fiscal 12 months based mostly on the present date. - GetCurrentFiscalStartYear
This calculates the 12 months by which the present Fiscal 12 months begins.
It took me a while (2–3 days of labor), however I managed to combine all columns into the date desk, which I contemplate helpful in most situations.
However the fundamental ideas within the M-language added further work and complexity, which isn’t wanted, for instance, in SQL.
However as a substitute of copying all of the M-Code right here, I will provide you with entry to the Energy BI file containing all the resolution with the date desk.
What’s subsequent?
Nicely, now you’ll be able to take all the M-Code, copy it right into a Information Circulate, and share it throughout your organisation.
To permit entry to your Information Circulate, granting Viewer permissions to customers within the Workspace is enough.
This manner, you’ve a single centralised model of the date desk that everybody can use.
That is the most important level which makes this method very helpful.
It’s the identical as when you’ve a centralised information platform, the place you construct a date desk. However since not all people has this, utilizing a Information Circulate is an efficient center floor.
In my work with Information Flows, I discovered that troubleshooting a failed import could be cumbersome. I’ve discovered that error messages could be minimal and will miss essential particulars.
Which one to make use of?
What do I like to recommend utilizing?
First, when you’ve a centralised information retailer, whether or not on-premises or cloud-based or if it’s a relational database or one other information retailer, use this to construct your date desk.
As I already talked about, there isn’t any query about this.
In a Self-Service BI state of affairs, or when the corporate isn’t that giant, the choice isn’t that simple.
First, it relies on the obtainable expertise.
After constructing the date desk in Energy Question, I discovered that it’s a lot simpler to construct a date desk in DAX than in Energy Question.
The capabilities of DAX make it simpler to construct a date desk than with M-Code in Energy Question.
I can outline the desk in a single DAX assertion and add advanced logic in further calculated columns.
However every DAX date desk is native to every Energy BI semantic mannequin. Subsequently, you find yourself with a number of date tables that may diverge from each other.
However as quickly as you’ve a number of groups constructing Energy BI options, it may be useful to create a single central date desk in a single Workspace and share it with all groups.
When somebody wants a brand new characteristic within the date desk, it will likely be added to the central desk, and everybody can profit from it.
After all, that is legitimate for any variant of centralised date tables.
In such circumstances, the information mannequin developer can all the time resolve which columns to import, avoiding the import of pointless columns into the information mannequin.
Conclusion
Now you already know the alternative ways to construct a date desk.
You resolve among the many obtainable prospects.
However it will likely be tough to modify from an area DAX desk to any centralised tables.
You must contemplate as early as potential which method you’ll go to keep away from the extra work of switching between them.
Take your time and discuss with all workforce members or potential mannequin creators to decide on the proper method.
It is not sensible to resolve to construct a centralised date desk when nobody makes use of it.
So, be certain that everyone seems to be on board with utilizing the central date desk.
References
Right here, the Microsoft documentation about {custom} capabilities in M:
https://study.microsoft.com/en-us/powerquery-m/m-spec-functions
A web page on Microsoft Study {custom} capabilities:
https://study.microsoft.com/en-us/power-query/custom-function
A great rationalization by Depraved Sensible Information:
https://www.wickedsmartdata.com/articles/custom-m-functions-power-query
If you happen to want a video to study, this one explains {custom} capabilities from the bottom up:
This video asks the query of when {custom} capabilities are helpful:
This exhibits you how one can resolve a problem, together with a really sensible method on how one can develop a {custom} operate simply:





