Sub topic 7
Sorting month names chronologically
This chapter assumes you can work in Power BI Desktop's Table and Model views and write a calculated table in DAX. It also assumes you already have a Date table with a Date column, as built earlier in this tutorial. Here you fix a problem that appears as soon as you put a month name on a chart axis: the months come out in alphabetical order.
Why month names sort wrongly
Power BI sorts a text column by comparing the characters of its values. The values Jan, Feb, and Mar are text, so the engine knows nothing about calendars. A chart that shows Month on its axis gets this order:
| Position | Month shown | What you expected |
|---|---|---|
| 1 | Apr | Jan |
| 2 | Aug | Feb |
| 3 | Dec | Mar |
| 4 | Feb | Apr |
| 5 | Jan | May |
| 6 | Jul | Jun |
The same happens with weekday names (Fri, Mon, Sat...) and with any label that is not naturally alphabetical. The fix does not change the text. You tell the model that the text column should be ordered by a second, numeric column.
Add a numeric key for every text column that needs ordering
Each text column that must follow a calendar order needs a numeric partner. Put both columns in the same table, and generate them from the same date so they cannot disagree.
This calculated table extends the one from the previous chapters. It adds a weekday pair and a pair for labels that include the year.
Date =
ADDCOLUMNS (
CALENDAR ( DATE ( 2020, 1, 1 ), DATE ( 2026, 12, 31 ) ),
"Year", YEAR ( [Date] ),
"Month Number", MONTH ( [Date] ),
"Month", FORMAT ( [Date], "MMM" ),
"Year-Month Number", YEAR ( [Date] ) * 100 + MONTH ( [Date] ),
"Month Year", FORMAT ( [Date], "MMM yyyy" ),
"Weekday Number", WEEKDAY ( [Date], 2 ),
"Weekday", FORMAT ( [Date], "ddd" )
)Three details in this code matter:
WEEKDAY ( [Date], 2 )returns 1 for Monday through 7 for Sunday. The default return type counts Sunday as 1, so pass2if your weeks start on Monday.Year-Month Numbermultiplies the year by 100 and adds the month, so March 2024 becomes202403. The numbers increase in the same order as the calendar.FORMATuses the language of the current environment to produce names. On a machine with another locale you may getjanv.instead ofJan. If you share the file across regions, add a culture as the third argument, for exampleFORMAT ( [Date], "MMM", "en-US" ).
The same columns in Power Query
If you built the table in Power Query, add the pairs with Table.AddColumn. This query is complete and returns a table with the sort keys already typed as whole numbers.
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}}),
AddMonthNumber = Table.AddColumn(Typed, "Month Number", each Date.Month([Date]), Int64.Type),
AddMonth = Table.AddColumn(AddMonthNumber, "Month", each Date.ToText([Date], [Format = "MMM", Culture = "en-US"]), type text),
AddYearMonthNumber = Table.AddColumn(AddMonth, "Year-Month Number", each Date.Year([Date]) * 100 + Date.Month([Date]), Int64.Type),
AddMonthYear = Table.AddColumn(AddYearMonthNumber, "Month Year", each Date.ToText([Date], [Format = "MMM yyyy", Culture = "en-US"]), type text)
in
AddMonthYearSet Sort by column
The numeric column does nothing until you link it to the text column. Do this once per pair.
- Open Table view and select the
Datetable. - Click the
Monthcolumn header. - On the Column tools ribbon, choose Sort by column, then pick
Month Number. - Repeat for
Month Year(sort byYear-Month Number) andWeekday(sort byWeekday Number).
You can also do this in Model view. Select the column, open the Properties pane, expand Advanced, and set Sort by column.
The setting belongs to the column in the model. Every visual that uses Month now orders it by Month Number, and you do not set it per chart. A slicer, a matrix row, and a line chart axis all follow it.
After the link works, hide the numeric columns from report view. Report authors should drop Month onto a visual, not Month Number. A hidden column still works as a sort key. Hiding it also stops people from accidentally summing it, because Power BI treats whole-number columns as summable by default.
The rule that decides whether a pair is valid
Power BI accepts a sort column only if the pairing is consistent. For each value of the text column, the sort column must hold exactly one value. In other words, the relationship from text to number is many-to-one or one-to-one.
| Text column | Sort column | Valid? | Reason |
|---|---|---|---|
| `Month` (`Jan`) | `Month Number` (1) | Yes | Every row with `Jan` has 1, across all years. |
| `Month Year` (`Jan 2024`) | `Year-Month Number` (202401) | Yes | Each label has one key. |
| `Month` (`Jan`) | `Year-Month Number` (202401, 202501...) | No | `Jan` maps to a different number in every year. |
| `Month Year` (`Jan 2024`) | `Month Number` (1) | Technically accepted, but wrong | Every January 1 sorts together, so years interleave. |
The third row is the most common mistake. Power BI refuses it and shows an error that says there are multiple values in the sort column for a single value in the text column. The fourth row is quieter. Different labels can share one number, and the model allows that. The resulting order mixes years, so check the visual after you set it.
The reverse is also worth knowing. Two different text values can share a number, such as Jan and January both at 1. This is allowed, but it is rarely what you want.
Check the mapping before you blame the model
When Power BI rejects a pairing, the cause is almost always a text value that maps to more than one number. This query lists any such Month values. Run it in DAX query view.
EVALUATE
FILTER (
ADDCOLUMNS (
VALUES ( 'Date'[Month] ),
"Numbers", CALCULATE ( DISTINCTCOUNT ( 'Date'[Month Number] ) )
),
[Numbers] > 1
)An empty result means every month name has exactly one number, so the pair is valid. Any row returned is a bad pair. The CALCULATE inside ADDCOLUMNS is required. It turns the current text value into a filter, so DISTINCTCOUNT counts the numbers for that value only.
Sorting the year-month label: do you need a key?
The label FORMAT ( [Date], "yyyy-MM" ) sorts correctly as plain text, because the year comes first and the month has two digits. 2024-02 sorts before 2024-10. So for that one format you can skip the sort column.
You still need one for labels that put the month name first or use names, such as Mar 2024. Alphabetically, Apr 2024 comes before Jan 2024. If you want readable labels, use a numeric key such as Year-Month Number.
Common problems
- The axis is still alphabetical after setting the sort. Check that the visual uses the text column from the date table, not an auto-generated date hierarchy or a copy of the column in another table. Sort by column does not carry over to a column you duplicated in another table.
- The sort column option is greyed out or the pair is rejected. Run the check query above. Look for a key that varies within one text value, as in the third row of the table.
- Months appear in the right order but a visual sorts by value. A visual's own sort overrides the model's default. Open the ... menu on the visual and choose Sort axis >
Month, then Sort ascending. - A slicer shows
Decfirst in a fiscal calendar. For a fiscal year, create a numeric key for the month's position in the fiscal year, such asFiscal Month Number, and sortMonthby that column. A text column can have only one sort column. If you need both calendar and fiscal orderings, create two text columns. - A column has no obvious partner. Add one. Cost is small, because each key is one integer per row, and a daily table has at most a few thousand rows.
Exercise
A colleague adds Month Year (for example Mar 2024) to the date table and sets it to sort by Month Number (1 to 12). The model accepts the setting, but a line chart over three years looks wrong. Describe what the chart shows and give the fix.
Show answer
Every row labelled with a January, in any year, has a sort value of 1, so all Januaries sort ahead of all Februaries. The labels from different years interleave instead of running in time order. Add a column such as Year-Month Number = YEAR ( [Date] ) * 100 + MONTH ( [Date] ), then set Month Year to sort by Year-Month Number. Each label now has one key and the keys rise with the calendar.
Exercise
You want a Monday-first weekday axis. Write the two calculated-column expressions for Weekday Number and Weekday, and say which column gets the Sort by column setting.
Show answer
Weekday Number = WEEKDAY ( [Date], 2 ) and Weekday = FORMAT ( [Date], "ddd" ). The 2 makes Monday 1 and Sunday 7. Select the Weekday column and set Sort by column to Weekday Number. The numeric column is the sort key and is the one you hide.