DAX measure to extract summed quantity values for selected weeks only - powerbi

I have production figures which sum the quantity of parts produced by each workstation on a weekly basis. These are shown in a matrix with workstation number on the rows and week numbers across the columns.
I want to be able to select 2 weeks and then
Display all the weeks in the range selected by a slicer.
Show the quantity values for only the first and last selected weeks.
The first part is working using a simple Week Slicer.
The second part, however, always shows the totals for all the selected weeks rather than the 2 individual week quantities.
In this example I have selected weeks 4 and 9 and therefore the expected values for quantities are 11,505 and 49,425 as shown in the Good Qty data with red frames.
The measures to extract the fist and last selected week numbers are working:
SelWeek1 = FIRSTNONBLANK(VALUES(vLink[Week]),0)
SelWeek2 = LASTNONBLANK(VALUES(vLink[Week]),0)
My measures for the week quantities are:
IF([SelWeek1]>0,
CALCULATE([Sum vGood Qty],FILTER(vLink, vLink[Week] = [SelWeek1])),
0
)
and
SelWeek2 Qty =
IF([SelWeek2]>0,
CALCULATE([Sum vGood Qty],FILTER(vLink, vLink[Week] = [SelWeek2])),
0
)
What am I missing?

Try to use below measures:
SelWeek1 = MIN(vLink[week])
Measure =
VAR _selWeek = [SelWeek1]
VAR result =
CALCULATE(
[Sum vGood Qty],
vLink[Week] = _selWeek
)
RETURN
result
and for selected week 2 change min to max in the first measure and _selWeek variable in the second measure respectively.

Related

PowerBI Running Total in Matrix based on Date

I have a matrix in PowerBI with two row filters (name and team) and columns as 12 dates starting from current month. I have a measure that I display for each month, but I want it to display as a running total rather than just as the value for each month.
This is the code I'm currently using:
Rolling 12 Month = calculate([12 Month],filter(all(Planning[Month]),Planning[Month]<=max(Planning[Month])))
where Planning[Month] defines the column header and 12 Month is this measure:
12 Month = sum([12MonthK])
where [12MonthK] is just a column of values.
The only code I've gotten to actually create a running total is this:
RTTest = If( Not ISEMPTY(Planning), VAR _maxDate = max(Planning[Month]) Return calculate( [YTD 12 Month], Planning[Month]<=_maxDate, all(Planning)))
but this running total just completely ignores any filters (the running total is the same for each name/team combo).

How i can compare last week average to todays data in Power BI visual?

I want to show an hourly score for today that refreshes every hour. I built it and it works, but now I want it to compare the hourly average for the last week and if it was higher it shows a red arrow up if lower it shows a green arrow down. I don't have a problem adding the arrows as it's very easy, but I've previously added a column to the query that shows if day = today and then used it as a filter inside the visual to show today's data, so when I try to compare the results the filter also affects the calculation I created:
Measure = calculate(average(rawdata[contacts]),rawdata[Week to Average = 1)
week to average is the column that tells if the week was the previous week is simply if(weekcolumn=weeknum(today())-1,1,0)
Do you know any way i can compare last week average to todays data?
Also visual that i used is a matrix
This is just an idea. So if it is enough to solve the case then ok. If it's not it, then, please, add more info about your data table - a screenshot or sample data. how you calculate your average and what do you mean by average? At least what kind of data you are dealing with is it a sum of some values per day, do you have a different number of values for each day? etc.
measure 1:
averContacts = AVERAGE(rawdata[contacts]) -- no CALCULATE()
measure 2:
avrToday =
CALCULATE(
[averContacts]
,TreatAS({TODAY()}, yourTable[DatesColumn])
)
measure 3:
aveLastWeek =
VAR prevWeekEnd = TODAY() - WEEKDAY(Today(),2) -- 2 -> Mon-Sun week format
VAR prevWeekStart = prevWeekEnd - 7
VAR DatesLastWeek = CALENDAR(prevWeekStart ,prevWeekEnd)
RETURN
CALCULATE(
[averContacts]
,TreatAS(DatesLastWeek, yourTable[DatesColumn])
)
measure for your visual
lastWeek_vs_Today = DIVIDE(avrToday ,aveLastWeek)

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])

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

Retrieving parameter from relative date Slicer Power BI

I have a calculation that is being done on a weekly basis (x+y/x*40) . 40 is the number of hrs worked per week and x is the num of weeks selected.
I have a relative date slicer using which the user will select the number of weeks. The catch is that there are two kinds of relative weeks - one from the present day and one is the entire week.
If the user selects 2 weeks it will be (x+y/2*40).
I have a calculation called
Tot Weeks = DATEDIFF(MIN( DimDate[Calendar Date] ), MAX( DimDate[Calendar Date]), week )
However, this doesn't work well if I select 'Weeks(Calendar Date)' in the drop down. For the value to be right, I created
Num weeks = DISTINCTCOUNT(DimDate[CalendarWeekOfYear])
Num weeks works fine only when 'Weeks(Calendar Date)' is selected. I am trying to retrieve the parameter passed to the slicer to get my values right.(whether the user selects 'Weeks(Calendar Date)' or 'Weeks' in the slicer).Is there a way to retrieve this or
Is there a way to combine these two?
If you have a slicer like with Weeks (Calendar Date) and Weeks as the two options in the column Slicer[WeekType], then you can pass your selection into a measure like this:
Weeks =
VAR WeekType = SELECTEDVALUE(Slicer[WeekType], <default>)
RETURN IF(WeekType = "Weeks", [Tot Weeks], [Num weeks])