Creating an measure to compare week-over-week developments - powerbi

My dataset includes information from at 26 different weeks. It lists all the open items from an accounts receivable database for each of the 26 weeks. Each of the report dates is exactly 7 days apart.
I am trying to compare the current receivables with the amount of the last week.
I thought that I will just extract the last report date with
LastReport:=LASTDATE(Report Date)
which gave me indeed the last report date. I go back 7 days with
PriorWeek:=DATEADD(LastReport;-7;DAYS).
This worked fine.
However, when I try to calculate the sum of last week using
CALCULATE(SUM(Total AR);Reportdate=PriorWeek)
I can an error that I cannot compare date and text fields.
I have checked the report date column is set to date.
What am I doing wrong?

I would say 'No need of ranking the Dates'. My solution is below using calculated columns:
Amount Variance =
VAR _PrevBlank =
ISBLANK ( [PrevWeek Amount] )
VAR _Amount = [Amount]
VAR _PrevAmount = [PrevWeek Amount]
VAR _Variance =
IF ( _PrevBlank, 0, _Amount - _PrevAmount )
RETURN
_Variance

I would suggest creating a date index using RANKX
RankDate = RANKX(Table1,Table1[Report Date],,ASC)
Then you can either create a calculated column that holds the previous week value
PreviousWeekCol = LOOKUPVALUE(Table1[Total AR],Table1[RankDate],Table1[RankDate]-1)
Or create a calculated measure that holds the prior week value
PreviousWeekMeasure =
VAR MaxDateIndex = MAX(Table1[RankDate])
RETURN CALCULATE(SUM(Table1[Total AR]),Table1[RankDate]=MaxDateIndex-1)

Related

PowerBi DAX measure to sum duration of timespans filtered by current slicer

I need a DAX measure that gives me the sum of durations for multiple categories restricted by a date slicer.
In this simplified example there are 2 categories with 3 subcategories each. A DateTime Slicer on the dashboard is set to the timespan of 2nd of January 2021 noon to 6th of January midnight. I need the summed up duration of all categories in this timespan.
Input data:
A table containing multiple rows for each category with a start date and an end date.
The complicated part is that there are pauses between the timestamps.
Desired output:
A table on the dashboard containing the category and a calculated measure for the summed up duration during the sliced timespan.
When changing the slicer the meaure shall change as well.
My current solution for this problem is an M formulato create a list of all days in each timespan and to unpivot all lists. In the dashboard the count of rows gives you the number of days in the selected timespan. This solution though reqires a much larger input table and soes not work if you want to be exact on the second, only on days.
I tried so solve this via a measure but didn't make any progress worth showing here.
all datetime values are in the format dd.mm.yyyy hh:mm:ss (24h system)
I found a way to do it by using 2 measures.
First measure calculates the time during the timespan for each element:
I use one Date Table only consisting of all dates available which is the input for the slicer and the data Table called "Data".
duration_in_timespan_single =
VAR MinTs = MIN ('Date'[Date])
VAR MaxTs = MAX ('Date'[Date])
VAR MinUtcMin = MIN ('Data'[Date_Start])
VAR MaxUtcMax = MAX ('Data'[Date_End])
RETURN
IF(
AND(MinUtcMin >= MinTs, MinUtcMin <= MaxTs),
IF(
MaxUtcMax <= MaxTs,
CONVERT((MaxUtcMax-MinUtcMin),DOUBLE),
CONVERT((MaxTs-MinUtcMin),DOUBLE)),
IF(
MinUtcMin < MinTs,
IF(
MaxUtcMax > MinTs,
IF(
MaxUtcMax <= MaxTs,
CONVERT((MaxUtcMax-MinTs),DOUBLE),
CONVERT((MaxTs-MinTs),DOUBLE)
),
0
),
0
)
)
The second measure just sums up the first for each category:
duration_in_timespan = SUMX('Data',[duration_in_timespan_single])

Create New Column containing value based on conditions on date and hour

I have a table in my power BI with the following fields :
Preview of the data:
The column "platform" has 3 possible values : application, shop, website
"day" is of type Date
"hour" is of type "Date/Time" (same information as "day" + has the hour)
I added a measure to calculate the conversion_rate (orders/visits):
conversion_rate = DIVIDE(SUM(Table[orders]), SUM(Table[visits]))
Then I calculated for every day the conversion_rate from 7 days ago (to be able to compare them):
conversion_rate_7_j = CALCULATE(Table[conversion_rate],
DATEADD(Table[day],-7,DAY)
)
Now my data looks like this:
What I want to do is calculate the conversion rate from 7 days ago but for the same hour.
However I couldn't find a function that substracts field of type Date/Time while taking in consideration the hour.
A solution I thought of is to calculate orders and visits -7 days same hour separately and then divide them to have the conversion rate -7 days same hour:
orders_7_j_hourly =
VAR h = Table[hour] - 7
VAR p = Table[platform]
Return CALCULATE(
MAX(Table[orders]),
Table,
Table[hour] = h,
Table[platform] = p
)
Since my data is grouped by hour (Date/Time) and platform,
And since sometimes for a certain hour I have values for the platform = "application" but not "shop",
My function did not work especially that I am using MAX, this associated the number of orders to the wrong platform.
Can you please help ?
Sample data : https://ufile.io/y1blqgqn
Datetime values are stored in units of days. Thus you can simply shift hour by 7 in your measure.
conversion_rate prev_week =
VAR CurrHour = SELECTEDVALUE ( Table1[hour] )
RETURN
CALCULATE (
[conversion_rate],
ALL ( Table1[day] ),
Table1[hour] = CurrHour - 7
)
Sample results:
Did you try to use HOUR function ??
conversion_rate_7_hour = CALCULATE( [conversion_rate],
FILTER( ALL(Table),
SELECTEDVALUE(Table[day]) - 7 = Table[day]
&& HOUR(SELECTEDVALUE(Table[hour]) - 7) = HOUR( Table[hour])
))
When we put Table[hour] to visualization it should work.
Ps. best pratice => if your refer to measures in your calculations,do not include the table prefix
You can create an additional column called hour in your dataset
Once you have that, you bring the hours in the viz, the following measure can give you what you want
convRate-7 = CALCULATE([convRate],DATEADD('Table'[day],-7,DAY))

How to create Last 12 months flag for grouped data in power bi

I have a table where where I want to create last 12 months flag column from the latest date available in each country. I have tried many Dax formula without success.
My table looks like below:
Here Y indicates the dates falls under last twelve months.
Please help me to find this flag.
You can create a calculated column to validate the date falls within the last 12 months, for each country. First calculate the maxDate for each country, then ensure the date is greater than the MaxDate with an if statement
Last 12 Months =
VAR MaxDate = CALCULATE (
MAX ( Country[Date] ),
ALLEXCEPT ( 'Country', 'Country'[Country] )
)
RETURN
IF (
Country[Date]> DATE(YEAR(MaxDate)-1, Month(MaxDate), Day(MaxDate)) ,1,0
)
This will then give you a filterable column to work from

HR Employee Count with Slicing by Dimensions - Slowly Changing Dimension

I need to calculate headcount while keeping the measure sliceable by any dimension connected to the fact table. Given the nature of my tables and model, what I need to do is a point in time calculation on a Slowly Changing Dimension Type 2.
I managed to make it work using the function KEEPFITLERS, but I need a more scalable function that wouldn't require me to list all the dimensions I want to slice by.
Here is my PowerBI file with sample data: https://gofile.io/d/smS2Hr
Here is a simplified sketch (image) of my model: https://ibb.co/fQYpsdx
Background:
The first measure I am calculating is the number of Employees at the Start of the Period (Employees SoP). If the end-user selects in PowerBI the whole month of January 2020, the Start of the Period is Jan 1st, 2020. Hence, "Employees SoP" for the month of Jan 2020 will give the number of employees on Jan 1st, 2020.
The formula below calculates the correct values for Employees SoP:
Employees SoP =
VAR MinDate = MIN ( 'Date'[Date]) //Mininum date selected by end-user in PowerBI
VAR Result =
CALCULATE (
DISTINCTCOUNT(Fact[EmployeeId]),
FILTER(ALL('Fact'), 'Fact'[EffectiveStartDate] <= MinDate
&& IF(ISBLANK('Fact'[EffectiveEndDate]), date(2050,1,1), Fact[EffectiveEndDate]) > MinDate
))
RETURN
Result
The problem with the formula above is that, because of the ALL function, the measure is not sliceable by any dimension, i.e., Pay Class and Employment Status (the same number repeats itself).
Results:
Hence, I created this other measure using KEEPFILTERS, and it works perfectly.
Employees SoP KEEPFITLERS =
VAR MinDate = MIN ( 'Date'[Date]) //Mininum date selected by end-user in PowerBI
VAR Result =
CALCULATE (
DISTINCTCOUNT(Fact[EmployeeId]),
FILTER(ALL('Fact'), 'Fact'[EffectiveStartDate] <= MinDate
&& IF(ISBLANK('Fact'[EffectiveEndDate]), date(2050,1,1), Fact[EffectiveEndDate]) > MinDate
), KEEPFILTERS(PayClass), KEEPFILTERS(EmploymentStatus))
RETURN
Result
The problem with this formula is that I have to list all the dimensions I want to slice by ( e.g., PayClass, EmploymentStatus) inside the DAX formula. This is not very scalable.
I did some experimenting with REMOVEFILTERS but it looks like it does not work with DirectQuery for now, so it wouldn't solve my production problem. Link:
https://learn.microsoft.com/en-us/dax/removefilters-function-dax
QUESTION:
How can I write this measure using an alternative to KEEPFILTERS with which I wouldn't have to list each dimension I want to slice by?
Thank you!
I just managed to solve my problem. I made both relationships to the Dates table "inactive". With that, I could remove the "ALL" function in the DAX formula and now it not only calculates the correct values, but it also slices nicely. I will have to use the USERELATIONSHIP function to calculate more complex measures but, in most of the cases, this simple solution works like a charm.
Employees SoP without ALL =
VAR MinDate = MIN ( 'Date'[Date]) //Mininum date selected by end-user in PowerBI
VAR Result =
CALCULATE (
DISTINCTCOUNT(Fact[EmployeeId]),
FILTER('Fact', 'Fact'[EffectiveStartDate] <= MinDate
&& IF(ISBLANK('Fact'[EffectiveEndDate]), date(2050,1,1), Fact[EffectiveEndDate]) > MinDate
))
RETURN
Result

Power BI: Count numbers by Today, and the count numbers of the previous years at the same date

I'm new to Power BI and DAX.
I want to show the total ID count of this year and the total ID counts of previous years at the same dates each of which is associated with a different Category_Number.
The below tables show the original data set (1st table) and the result table (2nd table) I would like to have.
enter image description here
enter image description here
Any ideas or suggestions will be greatly appreciated.
Thanks!
You want to filter and use SAMEPERIODLASTYEAR.
To get the values of one category you can do:
Category_Nbr 80 = CALCULATE(COUNTROWS(myTable),myTable[Category_Nbr] = 80)
for the value of this but for the previous year you could use your DATE TABLE if you have it, if not, use the automatic one. I'll assume you don't have one so use the automatic.
Category_Nbr 80 LY = CALCULATE([Category_Nbr 80],SAMEPERIODLASTYEAR(myTable[Effective_Date].Date))
With this you can do a comparison over time
Category_Nbr Count YoY = DIVIDE([Category_Nbr 80 LY]-[Category_Nbr 80],[Category_Nbr 80 LY])
You can just adapt the filter for other categories.
Consider having a look into Quick Measures really nice way to start learning DAX.
Below are two measures I created.
The Total_ID measure works well. It shows the total number of IDs that have the Category_Number =80 and Effecitve_Date < Today.
The Total_ID_LY measure shows the total number IDs that have the Category_Number = 70, but doesn't show the Effective_Date< The same data last year.
I want the Total_ID_LY measure to have two filters, Category_Number = 70 (80-10) and Effective_Date < The same data last year of today.
Any helps?
Thanks!
Total_ID = COUNT('myTable'[ID])
Total_ID_LY =
VAR CurrentCategory = SELECTEDVALUE ( 'myTable'[Category_Number] )
VAR PreviousCategory =
CALCULATE (
MAX ( 'myTable'[Category_Number] ),
ALLSELECTED ( 'myTable' ),
KEEPFILTERS ( 'myTable'[Category_Number] < CurrentCategory )
)
VAR Result =
CALCULATE (
[Total_ID],
'myTable'[Category_Number] = PreviousCategory
)
RETURN
Result