DAX Query to group column with getting its average of another column where date column is latest one - dax

Let's say I have a table which contains school data with schoolName, StudentCount, Year columns.
What I want is get average of studentCount for latest year by school.
It may possible that school 1 's latest year is 2021 where as school 2 's latest year is 1990.

This is probably late but I guess it can help someone.
The table is named SchoolData and the goal is to average the last record for each school across all schools.
DEFINE
VAR SchoolAndMaxYear = //LastYearForEachSchool
GROUPBY (
SchoolData,
SchoolData[SchoolName],
"YearValue", MAXX ( CURRENTGROUP (), SchoolData[YearValue] )
)
VAR StudentCountForSchoolAndMaxYear =
CALCULATETABLE (
SchoolData,
TREATAS ( SchoolAndMaxYear, SchoolData[SchoolName], SchoolData[YearValue] )
)
EVALUATE StudentCountForSchoolAndMaxYear
EVALUATE
ROW (
"AVGStudentCountLyBySchool", AVERAGEX ( StudentCountForSchoolAndMaxYear, SchoolData[StudentCount] )
)

Related

A single value for column .... cannot be determined

I have 2 tables for stock management. 1 for the list of stock and some other properties and 1 for the daily values (i have a relationship between both on the index of the stock).
I would like to have a weekly performance ie the value has increased/decreased by xx from the previous week.
So I created a table (weeklies) with a few rows which correspond to a week for each row. I have 2 columns: 1 is the beginning date of the week, 1 is the last date of the week.
Im creating a calculated third column with the sum of all the values at the beginning date of a given week :
CALCULATE (
SUMX ( Daily_Stock; [Price] * RELATED ( Stock_list[Qty] ) );
FILTER ( Daily_Stock; Daily_Stock[Date] = weeklies[begin_date] )
)
It works fine but I would like to exclude some stocks which were sold before the beginning date (i have other reasons to be able to achieve this) so I'm trying to multiply by 0 if it is the case for that specific stock.
CALCULATE (
SUMX (
Daily_Stock;
[Price] * RELATED ( Stock_list[Qty] )
* IF ( RELATED ( Stock_list[sold_date] ) < weeklies[begin date]; 0; 1 )
);
FILTER ( Daily_Stock; Daily_Stock[Date] = weeklies[begin_date] )
)
There I have the following error :
A single value for column sold_date in table Stock_list cannot be determined.
Tweaking around a little bit and I had the same error on the weeklies table.
Does anyone know what I should be doing here?
I can explain more, I wanted to avoid a too-long post.
thanks
I think the issue is the relation.
I assume the RELATED is based on the stock index you mentioned.
I think related stock_list[sold_date] returns all dates that RELATED stockID has ever been sold.
Which would mean you are trying to compare more than one date with weeklies[begin date].
image copied from powerpivotpro on using VALUES with IF in measures.
If i am right, you need another way of relating to your stocklist to get singular matches. I am not sure if the VALUES solution rob collie uses for measures will work here, but maybe it is worth testing. Rob collie powerpivotpro - Magic of IF(VALUES)

Ranking results from a SUMMARIZECOLUMNS operation

I created the following DAX code in DAX Studio which works correctly:
EVALUATE
SUMMARIZECOLUMNS(
'Florida Sightings'[Locality Id],
Hotspot[Subnational 1 Code],
Hotspot[Name],
'Calendar'[Month],
FILTER(Hotspot, Hotspot[Subnational 1 Code] = "US-FL"),
"Species Count", COUNTROWS(VALUES('Florida Sightings'[Common Name]))
)
The output looks like this, sorted by month and species count:
I would like to take the results of the SUMMARIZECOLUMNS and add a rank column based on species count for each locality Id and month. So, for the first locality Id (L127258) and Month (1), the rank would be 1. And, for the second locality Id (L123565) and month (1), the rank would be 2 etc.
The months run from 1 through 12 for each locality.
Without sample data to work with, I'm shooting in the dark a bit but try something along these lines:
ADDCOLUMNS (
SummaryTable,
"Rank", RANKX (
FILTER (
SummaryTable,
[Locality Id] = EARLIER ( 'Florida Sightings'[Locality Id] )
&& [Month] = EARLIER ( 'Calendar'[Month] )
),
[Species Count]
)
)

A way to filter a distinct set of columns using a measure from the same table - Tabular2017

Overview of the table in question
I need to get a distinct count of the column Fkey_Dim_Resource_ID that has holiday to spare.
My Table consists of five columns:
Resource_Allocated_Holiday_ID (Primary Key)
Fkey_Dim_Resource_ID
Fkey_Dim_HolidayYear_ID
Fkey_Dim_Company_ID
Allocated_Holiday_Hrs_Qty
Measure:
Allocated Holiday (Hrs):= Var X= SUM([Allocated_Holiday_Hrs_Qty])
Return if(X =0; BLANK();X)
This measure below then uses the above, and the holiday spent from another metric:
Remaining Holiday (Hrs):= Var X = 'HolidayEntry Numbers'[Allocated Holiday (Hrs)] - [#Holiday Hours]
Return if(X=0;BLANK();X)
And now, I would like a metric that gives me the distinct count of Fkey_Dim_ResourceID where 'Remaining Holiday (hrs)' >0.
I have tried a lot of different stuff, but cannot seem to get it right.
test:=
ADDCOLUMNS(
SUMMARIZE('HolidayEntry Numbers'
;'HolidayEntry Numbers'[Fkey_Dim_Company_ID]
;'HolidayEntry Numbers'[Fkey_Dim_Resource_ID];
'HolidayEntry Numbers'[Fkey_Dim_HolidayYear_Id]
)
;"RemainingHoliday"; sum( [Remaining Holiday (Hrs)])
)
I would like for a distinct count of Fkey_Dim_Resource_ID that has holiday left, that takes into account the context.
Thanks in advance.
With this measure:
test4 virker når ressourcen er med:=COUNTROWS (
FILTER (
ADDCOLUMNS (
VALUES ( 'HolidayEntry
Numbers'[Fkey_Dim_Resource_ID]);
"remholiday"; CALCULATE ( [Remaining Holiday
(Hrs)] )
);
[remholiday] > 0
)
)
I get the following result:
Result of the advice1
So the metric works, when in the context of a Resource, but not when in the context of a Fkey_dim_holiday_Year_ID.
Thanks ion advance.
Resources with remaining holiday hours =
COUNTROWS ( // counts rows in a table
FILTER ( // returns a table, filtering based on predicate
// below is unique values of the column in context, as a
// one-column table
VALUES ( 'HolidayEntry Numbers'[Fkey_Dim_Resource_ID] ),
[Remaining Holiday (hrs)] > 0 // keep rows meeting this criterion
)
)
As a matter of style, you should fully qualify column names as 'Table'[Column], and never fully qualify measure references, i.e. don't prefix with table name. This conforms with all style guides I know, and helps to ensure your code is unambiguous (since both columns and measures are referenced in square brackets).

Filter Dax Calculation based upon YTD Sum

In a Tabular SSAS Model, I'm trying to count the number of distinct customers that purchased a given product wtihin a YTD Timeframe. The table contains measures that aren't explicit sums, so I get the Cartesian Product of all products for each customer, regardless of no sales. I'm attempting to limit the count by filtering out customer / product combinations with YTD Sales = 0. However, I cannot get the FILTER to recognize the DATESYTD context. It only ever filters based upon Sales existing within the chosen calendar month. I've tried inserting the ALL function every which way.
This is what I have so far.
Measure:
CALCULATE (
DISTINCTCOUNT ( Fact[Customer] ),
DATESYTD ( Calendar[Date] ),
FILTER ( Fact,
CALCULATE ( [Sum of Sales], DATESYTD ( Calendar[Date] ) ) <> 0
)
)
This measure will, for example, count distinct customers purchasing a product in Month #5 if Month #5 is explicitly chosen. It will not, however, include a customer that purchased that item in Month #2 of the same year.
I think the following DAX should do the trick:
COUNTROWS(
FILTER(
VALUES(Fact[Customer]),
CALCULATE ( [Sum of Sales], DATESYTD ( Calendar[Date] ) ) <> 0
)
)
Also, make sure your 'Calendar' table has been marked as a date table. If, for some reason, you prefer not to mark it as a date table, rewrite the above DAX to:
COUNTROWS(
FILTER(
VALUES(Fact[Customer]),
CALCULATE ( [Sum of Sales], DATESYTD ( Calendar[Date] ), ALL('Calendar') ) <> 0
)
)
Edit: Do you have records in your fact table where [Sum of Sales] is 0? If not, then you could simplify and improve the performance considerably by writing:
CALCULATE(
DISTINCTCOUNT(Fact[Customer]),
DATESYTD( Calendar[Date] )
)
Again, if you haven't marked your 'Calendar' table as a date table, add ALL(Calendar) to remove the filter on specific calendar columns.

PowerBI: Use filter but avoid propoagation effect

I'm trying to calculate how much an employee is spending time on actual projects:
'billability' = [total hours worked on projects] / [total hours that the employee was available]
I'm given a schema like:
Tornado = (employee_id, date, project_id, hours, ..)
'public employee_schedule' = (employee_id, date, hours, ..)
'Tornado' is the table that records hours spent. 'public employee_schedule' is the table that records available hours per day per employee.
So to calculate billability, I have a measure in Tornado table:
billability= Sum(Tornado.hours)/Sum('public employee_schedule'.hours)
In powerBi desktop, I have a page where I do a range of analysis on Tornado, and it includes a date filter (Timeline control) that is tied to Tornado.date
The problem: after a date range is selected, rows on Tornado are filtered and if there is no work done by the employee in those dates, nothing is selected (0 hours worked), but the filter also propagates to 'public employee_schedule' and I get also 0 for hours available.
I should be using ALL with FILTER in the denominator, but how to access the dates chosen in Timeline control?
See screenshot below for data model.
I created a new AllDates(id, date) table with 1:* relationship with Tornado and 'public employee_schedule' on date column.
In my page, I use AllDates.date for filtering, which propagates to both Tornado and public 'public employee_schedule'.
Finally I use Format > Edit Interactions to avoid any other unwanted filters/slicers affecting my measure (that is shown in a KPI card).
Another solution could be something along this line (WorkDone is Tornado and HoursAvailable is 'public employee_schedule') :
billability =
VAR MinDate =
CALCULATE ( MIN ( WorkDone[date] ), ALLSELECTED ( WorkDone ) )
VAR MaxDate =
CALCULATE ( MAX ( WorkDone[date] ), ALLSELECTED ( WorkDone ) )
RETURN
(
SUM ( WorkDone[hours] )
/ CALCULATE (
SUM ( HoursAvailable[available_hours] ),
FILTER (
ALL ( HoursAvailable ),
HoursAvailable[date] >= MinDate
&& HoursAvailable[date] <= MaxDate
)
)
)

Resources