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. And here's the calculated column DAX script.
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.
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.
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.
The dates are now sorted correctly.
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. 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] ) )
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] )) )
IF(MONTH ( 'SalesOrder'[OrderDate] ) < 10, "0" & MONTH ( 'SalesOrder'[OrderDate] ), MONTH ( 'SalesOrder'[OrderDate] ))
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] )) )
Comments
Post a Comment