Calculate daily average including zero in Power BI - powerbi

I have a dataset of patients visiting several categories(SPECIALISM) of a hospital. A visit lasts a couple of hours each day. Each row in my dataset represents an hour that they are present for a certain hospital specialism.
Input
I want to calculate for each hour of the day, the number of patients that are present on average, per specialism, I used the following code (measure):
daggem = AVERAGEX(values('Date'[Date]),[distinctpat])
with distinctpat being a distinct count of patient IDs
This gives me almost the desired result, but the tales of the graph are too heavy (it shows an average of 1 patient during the night, but this 1 patient was there only on 1 specific day, normally it is zero. But the average, as I calculated, it does not include all other nights when there were zero patients. So I would like to obtain an average that is much lower (and more correct)
Output

You probably need an extra table with all the days and times. Based on the reports, you will be able to find the hours without visits
Here is an example of how to create a Date table with hours; Add relationship and use in calculation.
DatesWithHours =
var Dates = CALENDAR("2021-01-01 00:00:00", "2021-01-03 00:00:00")
var DatesHour =
GENERATE(Dates, (ADDCOLUMNS(GENERATESERIES(1,12,1),"Hours", [Date] + TIME([Value],0,0))))
return
DatesHour

That's the problem with AVERAGEX, it ignores blanks. Try a simple division instead.
daggem =
DIVIDE (
COUNTROWS ( TargetTable ),
COUNTROWS ( Dates )
)

Related

How to calculate the cumulative total of an average (calculated column)

I'm having a hard time to calculate the running / cumulative total of average values...
My idea is to emulate a sales campaign for a product that never had one, using the average by day of all the products from an specific brand; problem is the code I made is only repeating the numbers from the average, it's not summing them up:
This is how it's now:
This is how it should be:
I managed to filter the values I want to calculate the average for, and that's for an specific brand (this is not going to be replicated to all products, and in the end I want to merge this in another calculated column which will calculate the goal for all the products (including the exception, which are the ones that never had a sales campaign before).
here's the code for the average:
AllPlutoProductsAverage = MAXX(FILTER('f_Leads(teste2)', [percentage] = EARLIER(d_CT_Leads_RT[percentage]) && 'f_Leads(teste2)'[group_name]="Pluto"), 'f_Leads(teste2)'[registers_per_day] )
And here's the code for the cumulative/running total column:
VAR _NoCampaign_RT =
CALCULATE(
MAX( 'd_CT_Leads_RT'[AllPlutoProductsAverage ] ) ,
FILTER( 'f_Leads(teste2)' ,
AND( 'f_Leads(teste2)'[group_name] = d_CT_Leads_RT[group_name] ,
'f_Leads(teste2)'[course] = d_CT_Leads_RT[course]
) &&'f_Leads(teste2)'[course_closed_percentage] = d_CT_Leads_RT[percentage]
)
)
Any ideas on how I fix that...?
Thanks in advance!! :))
I tried:
quick measure for running totals, didn't work
custom code for running totals, still repeated the values
creating a separate measure for average and then mentioned it on the column's running total code, same result
tried building up a running total code by adding the average calculation into it as a variable, didn't work either
tried exporting the calculation to a measure, didn't work either
And by 'didn't work' I mean the column No_PreviousCampaign still shows the repeated values from AllPlutoProductsAverage

Average Days Outstanding of ALL tickets as of certain date

I am trying to figure out Dax for Average Days Outstanding taking into account all tickets that are open as of spec date to show trend over time.
How many days tickets are outstanding on average over the period of time and how many days outstanding on tickets as of 8/25/2020? In this case, I am taking as of today's date but I need to be able to calculate as of 8/1/2020 as well.
Per example below, I have manually calculated in excel the outcome that I am looking for but do not know how to create DAX formula to reflect that. I did it in excel to show what outcome I am trying to achieve.
In powerbi, I do have Calendar table with a date column and with relationship to ticket date.
As you can see, in my average formula I am taking into consideration all tickets that have current balance >0 as of 8/25/2020 and giving average counting prior rows ( prior tickets open as of 8/25/20).
Currently, I know to how to calculate DAX days outstanding which is difference between ticket dates and today on tickets with current balance >0 but I do not know how to include in my DAX prior days where tickets are outstanding as well.
Your help is greatly appreciated!
Try with the below logi-
running_average =
VAR current_row_date = MIN(your_table_name[payment date])
RETURN
AVERAGEX (
FILTER(
ALL(your_table_name),
your_table_name[payment date] <= current_row_date
),
your_table_name[outstanding amount column name]
)
I can see some value in "payment date" column is blank. They will produce wrong results here. You need to somehow make adjustment for those BLANK values to get correct results.

How can I calculate a monthly average including months with no records in Power BI

I'm trying to calculate a monthly average number of cases for each investigator. It might be over a quarter, year, or multiple years so it needs to respond to the visual or table context I drop it into. The base table has Case (individual case#), Investigator (person name), Date assigned (not shown), and from that date,month and year columns extracted and a YearMonth categorical column.
I create a caseCount measure as
caseCount = COUNT('Table'[Case])
I've tried several different ways to calculate the average over all months (in this case 4). Because Mary has cases in each month, her average is correct (1.75) but Sam's uses a denominator = 3, thus doesn't calculate correctly. (returns 1.3 instead of 1). How can I force the calculation to use the full number of months.
Additional notes:
There may be cases in the table that fall outside the date range I want so I've tried using a
Avg = CALCULATE(AVERAGE(caseCount), Table[Date] > #10/31/2019#)
I've also tried several variations using CALCULATE(DIVIDE(), [Date] > 10/31/2019. Everything seems to exclude those months when an investigator had no investigations assigned. I also tried connecting to a Date table and using the Distinct YearMonth value created there.
This is because the evaluation context.
I would define the measure as follow:
VAR _casecount = //count number of cases in the selected period, applied on the fact table
VAR _months = COUNTROWS(CALCULATETABLE(VALUES('Calendar'[Month]), ALLSELECTED('Calendar'))) //count number of months in the selected period
RETURN
_casecount/months
Update
I did not consider the scenario of multi-year periods involving May-2019 and May-2020. Then, let's reframe the solution using DATEDIFF:
VAR _casecount = //count number of cases in the selected period, applied on the fact table
VAR _firstCalendarDate = CALCULATE(MIN('Calendar'[Date], ALLSELECTED('Calendar'))
VAR _lastCalendarDate = CALCULATE(MAX('Calendar'[Date], ALLSELECTED('Calendar'))
VAR _months = DATEDIFF(_firstCalendarDate, _lastCalendarDate, MONTH)
RETURN
_casecount/months

Dax Finding date based on Criteria calculated Column

I couldn't find an answer for my issue elsewhere, so trying my luck here.
I have sales table and my final result should determine if there were sales made for same person in specific period of time, for example within 7 business days. for example:
For ID 123 I have to flag it that sale for products A,B,C where within specified period.
For ID 1234 only sales of products A and B meet the criteria product C was sold in irrelevant time frame.
I've created a date table with indicators that determine for each date if the date is a working day, but i am struggling to calculate the relevant last working day
For example: I need that for 01/01/2019 i will get 10/01/2019 date, based on NUMOFDAYS and FinalWorkday = TRUE, which basically means that i have to count NUMOFDAYS times TRUE statement for each date and return corresponding date.
After that step done I think that it would be pretty easy for me to determine if the sale for a person was made in specific time frame.
If someone can give me direction for that much appreciated
Thank you in advance
You could use a DateTable like this one:
I used the following DAX-expressions for the calculated columns:
nrDays = 7
isWorkDay = WEEKDAY('DateTable'[Date],2) < 6
rankWorkingDays = RANKX ( FILTER ( DateTable, DateTable[isWorkDay] = TRUE () ),
DateTable[Date] , , ASC )
LastWorkDay = LOOKUPVALUE ( DateTable[Date],
DateTable[isWorkDay], TRUE (),
DateTable[rankWorkingDays], DateTable[rankWorkingDays] + DateTable[nrDays])
This issue can be solved by the following, since three are non-working days/holidays we can filter them out via POWERQUERY, than add an Index Column and Another column Which is basically Index column + Number of days wanted, then simply merge duplicate of dates query on Index+number of days wanted column on Index column. And we get the correct date

Power BI Rolling Average

I've used the new Quick Measures feature of Power BI to build a 3 month rolling average calculation and it's working well. The equation is displayed below. However, when I try to use this metric in a time series visualization, the calculations are displaying three months past the current month, but I'd like for the calculation to stop at the current month.
I've played around with the __DATE_PERIOD variable to no avail. My date filter for the page is set to show all dates in the current months or 12 months prior via a calculated column on the date table.
Is anyone aware of how I can get the visualization to end at the current month?
Average Days to Close Rolling Average =
IF(
ISFILTERED('Date'[Date]),
ERROR("Time intelligence quick measures can only be grouped or filtered by the Power BI-provided date hierarchy."),
VAR __LAST_DATE =
ENDOFMONTH('Date'[Date].[Date])
VAR __DATE_PERIOD =
DATESBETWEEN(
'Date'[Date].[Date],
STARTOFMONTH(DATEADD(__LAST_DATE, -3, MONTH)),
__LAST_DATE
)
RETURN
AVERAGEX(
CALCULATETABLE(
SUMMARIZE(
VALUES('Date'),
'Date'[Date].[Year],
'Date'[Date].[QuarterNo],
'Date'[Date].[Quarter],
'Date'[Date].[MonthNo],
'Date'[Date].[Month]
),
__DATE_PERIOD
),
CALCULATE(
'Closed Opportunities'[Average Days to Close],
ALL('Date'[Date].[Day])
)
)
)
In order to limit what is displayed within your chart, you need to filter the applicable date field so it only displays the dates you desire. In this case, you only want it to include dates <= today.
In order to automatically filter it when it is refreshed, I typically add a custom DAX column to the date table that I can filer on. In this case it would be something along the lines of:
excludeFutureDatesInd = 'Date'[Date] <= TODAY()
You can then add a visual, page, or report filter selecting all dates where [excludeFutureDatesInd] = True.
Not sure if you're still having issues with this, but I'd like to share a hack fix for those landing here. I fixed this issue by filtering on the base data (in your example, this would be "Average Days to Close"). Set a visual-level filter to include only those items where Average Days to Close > 0, and you should get the extra dates cut off the end of the graph.
So long as all of your base data passes through the filter, you should be good.