Donate

Power BI Add Leading Zero (0) To Month In DirectQuery

Good noon!
I was recently confronted with an issue on dates not sorted correctly of which a date with this value 2020/10 (October 2020) appears in between of 2020/2 and 2020/1. This was based from an article I read on how to change the current date into a Current Month string and the data type for this calculated column is Text. As you can see from the image below, month of November which is the current month is translated as "Current Month". But October 2020 is in between January and February 2020 respectively.
Power BI Add Leading Zero (0) To Month In DirectQuery
And here's the calculated column DAX script.
Current Month =
IF (
    MONTH ( 'SalesOrder'[OrderDate] ) = MONTH ( NOW () )
        && YEAR ( 'SalesOrder'[OrderDate] ) = YEAR ( NOW () ),
    "Current Month",
    YEAR ( SalesOrder[OrderDate] ) & "/"
        & MONTH ( SalesOrder[OrderDate] )
)
Since my datasource came from SQL Server database and the storage mode is DirectQuery, I can't just use the Format() function. After analyzing the issue, I came up with a solution which is to check months that are less than 10, and add a leading zero to it.
Current Month = 
IF (
    MONTH ( 'SalesOrder'[OrderDate] ) = MONTH ( NOW () )
        && YEAR ( 'SalesOrder'[OrderDate] ) = YEAR ( NOW () ),
    "Current Month",
    YEAR ( SalesOrder[OrderDate] ) & "/" & IF(MONTH ( 'SalesOrder'[OrderDate] ) < 10, "0" & MONTH ( 'SalesOrder'[OrderDate] ), MONTH ( 'SalesOrder'[OrderDate] ))
)
But the script above will generate an error Function 'IF' is not allowed as part of calculated column DAX expression on DirectQuery models since the false value of this IF statement will return an integer instead of a string.
IF(MONTH ( 'SalesOrder'[OrderDate] ) < 10, "0" & MONTH ( 'SalesOrder'[OrderDate] ), MONTH ( 'SalesOrder'[OrderDate] ))
I added an additional code which is to add empty string before the MONTH ('SalesOrder'[OrderDate]) false value to make this work. See final script below.
Current Month = 
IF (
    MONTH ( 'SalesOrder'[OrderDate] ) = MONTH ( NOW () )
        && YEAR ( 'SalesOrder'[OrderDate] ) = YEAR ( NOW () ),
    "Current Month",
    YEAR ( SalesOrder[OrderDate] ) & "/" & IF(MONTH ( 'SalesOrder'[OrderDate] ) < 10, "0" & MONTH ( 'SalesOrder'[OrderDate] ), "" & MONTH ( 'SalesOrder'[OrderDate] ))
)
The dates are now sorted correctly.
Power BI Add Leading Zero (0) To Month In DirectQuery

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.