How to refer to a single value in a Calculated Column in a measure (DAX) - calculated-columns

I have a table(Data_all) that calculates daycount_ytd in one table.
[Date] is in Date Format.
[Fiscal Year] is just year. eg: 2016
Calculated Column
daycount_ytd=DATEDIFF("01/01/"&[Fiscal Year],Data_all[Date],day)+1
Im trying to create a measure that refers to this Calculated Column
Measure:
Amt_X Yield %:=[Amt X]/([Amt Y]/365* (Data_all[DayCount_YTD]))
I get the error that Data_all[DayCount_YTD] refers to a list of values.
How do i filter the expression to get a single value without using a aggregation function eg:(sum, median)?
Or perhaps, is there another way to achieve the same calculation?

You've arrived an a fundamental concept in DAX and once you've worked out how to deal with it then the solution generalises to loads of scenarios.
Basically you can't just pass columns into a DAX measure without wrapping them in something else - generally some kind of mathematical operation or you can use VALUES() depending on exactly what you are trying to do.
This measure will work OK if you use it in a PIVOT with the date as a row label:
=
SUM ( data_all[Amt X] )
/ (
SUM ( data_all[Amt Y] ) / 365
* MAX ( data_all[daycount_ytd] )
)
However you will see it gives you an incorrect total as it is in the latest for the entire thing. What you need is a version that iterates over the rows and then performs a calculation to SUM or AVERAGE each item. There is a whole class of DAX functions dedicated to this such as SUMX, AVERAGEX etc. You can read more about them here
It's not totally clear to me what the maths behind your 'total' should be but the following measure calculates the value for each day and sums them together:
=
SUMX(
VALUES(data_all[date]),
SUM(data_all[Amt X]) /
(SUM(data_all[Amt Y]) / 365 * MAX(data_all[daycount_ytd]))
)

Related

Sum columns in Power BI matrix

I am working on a matrix in Power BI and I am not figuring out how to sum each column recursively until the total:
And this should be the resulting matrix (as an example, rows):
Some clarifications:
The months (columns) are dynamically generated based on the transaction month. I could filter the data to get the same data for only three months.
"Nombre proveedor" stands for "Vendor name".
I don't care about "Total" row.
These are my values:
So, I think I should create a measure with DAX to replace "Accounting Balance" to sum the previous column (month) or show nothing (to avoid zeroes).
Searching on internet I found several sites to get the running totals by rows, but not by columns.
Any suggestions?
Try Something like this:
Maesure =
CALCULATE (
[Accounting Balance],
FILTER (
ALL ( 'table' ),
'table'[Transaction month] <= MAX ( 'table'[Transaction month] )
)
)

DAX average including zeroes

My question is that I'd like to calculate a daily average taking into account days with zeroes.
Let me clarify it:
I'd like to calculate the average daily value of units for each category, with the following table:
When I sum up the values for each day and category, I get:
I'd like to include in the average calculation the zeroes.
I use the following code:
SUMMARIZE(
Data,
Data[Category],
"Average",
AVERAGEX(
SUMMARIZE(
Data,
Data[Date],
"Sum of Units",
SUM(Data[Units])
),
[Sum of Units]
)
)
But the problem is that for category B it doesn't take into account those days with 0s.
Could you please guide me how to solve it?
Thanks in advance!
Jorge
One way to solve it would be to create a calendar table, which can then be used to count the number of days in any of your grouping periods. This also means you can use non standard calendars, for example something like a 4-4-5
With a calendar table created you can leverage the FIRSTDATE and LASTDATE functions in DAX.
I recommend adding a past dates column to the calendar table, which can be created using DAX with the following formula. The today function in DAX when used in a calculated column will only evaluate when the model is updated.
In my example I created a calculated column in the date table called Past_Dates
Past_dates =IF( TODAY() > [Date], TRUE(), BLANK())
So for example if I create the following measures, the Today one just being used for illustration.
Start_date:=FIRSTDATE( Dates[Date] )
End_Date:=LASTDATE( Dates[Date])
Today:=TODAY()
EndPhased:=CALCULATE( LASTDATE( Dates[Date] ), Dates[Past_dates] = TRUE())
Which when added to an empty pivot table evaluate to the following.
Note that you would want to have year somewhere in the pivot if you have multiple years of data.
The idea of having the Past flag is to keep from counting days where they would not be any data due to being in the future. So for example in September it would only use 11 days of sales and not the full 30.
As the below example shows, the finding of the start and end date even work on a Quarter basis.
So now that we have a way to get the Start and End date of a period, the next step is adding it into our Calculated measure.
In the below example, we are iterating though every unique Category name. Within the category, we are summing the units sold, and then dividing by the number of days between EndPhased and Start_Date + 1. Then averaging the results by the number of categories that have data in that period.
Average:=AVERAGEX (
VALUES ( Data[Category] ),
CALCULATE ( DIVIDE ( SUM ( Data[Units] ), [EndPhased] - [Start_date] + 1 ) )
)
It seems to me that you need to have an underlying row with the zero value in it (in your initial Data table). Right now, you don't actually have a zero value for B on 02/01/2017. If you add a row with the values | 02/01/2017 | B | 0 | I believe you will see that the average accounts for it. As things stand for you right now, I believe the pivot table actually reflects no value (blank) rather than zero value, so the zero isn't currently counted for the average.
I think the best way is to add the missing zeroes, using UNION function:
SUMMARIZE(
Data,
Data[Category],
"Average",
AVERAGEX(
UNION(
SUMMARIZE(
Data,
Data[Date],
"Sum of Units",
SUM(Data[Units])
),
ADDCOLUMNS(
EXCEPT(
ALL(Data[Date]),
VALUES(Data[Date])
),
"Sum of Units",
0
)
),
[Sum of Units]
)
)

Compute a calculation over SUMMARIZE in DAX

I have the following scenario. I have students who pass test. They may have more than 1 supervisor at the same time. I would like to create a calculation in DAX that computes the average score at every level (i.e. department, supervisor, student).
The original table contains a single test per student, but I've "left joined" this table with a newly created one, student-supervisor, so I can compute also the score over the supervisor. The problem is when I compute the average score per department, because it contains all the duplicates I created with this new table.
These are my tables:
And this is my model:
The obvious DAX that just computes the average of the score works fine for Students and Supervisors on the PivotTable below, but it's wrong at a department level:
Avg Score:=AVERAGE(score[Score])
At this point I've tried something like the following, but without success. My point was to create a dynamic table with SUMMARIZE that groups by testid and does the average of score. Then I wanted to average that again, which would be the correct score and convert that 1column-1row into a numeric value. But this doesn't work, and I'm not sure why:
Avg Score= VAR ThisTable=SUMMARIZE(score,score[TestId],"IndividualScore",AVERAGE(score[Score])) RETURN SUMMARIZE(ThisTable,"AvgScore",AVERAGE([IndividualScore]))
This is the way I'd approach it.
First create a measure like the below to get the score in each context:
Sum Score := MAX(Score[Score])
Then create the average calculation measure:
Avg Score :=
DIVIDE (
SUMX ( DISTINCT ( Score[Student] ), [Sum Score] ),
DISTINCTCOUNT ( Score[Student] )
)
Note the Sum Score measure is required because the Avg Score measure uses it to perform the calculation.
You will get something like this Matrix (Pivot Table) in Power BI:
Let me know if this helps.
Alright, so thanks to alejandro's idea I could figured out the answer. Basically I'm creating an on-the-fly table with a group by test id and the average score (i.e. the real score). Then I'm using AVERAGEX to compute the average of those test. Here's the DAX code:
Avg CSAT:=VAR ThisTable=SUMMARIZE(score,score[TestId],"SumOfScore",AVERAGE(score[Score])) RETURN AVERAGEX(ThisTable,[SumOfScore])

Calculated Measure Based on Condition in Dax

I have a requirement in Power Pivot where I need to show value based on the Dimension Column value.
If value is Selling Price then Amount Value of Selling Price from Table1 should display, if Cost Price then Cost Price Amount Should display, if it is Profit the ((SellingPrice-CostPrice)/SellingPrice) should display
My Table Structure is
Table1:-
Table2:-
Required Output:-
If tried the below option:-
1. Calculated Measure:=If(Table[Category]="CostPrice",[CostValue],If(Table1[category]="SellingPrice",[SalesValue],([SalesValue]-[CostValue]/[SalesValue])))
*[CostValue]:=Calculate(Sum(Table1[Amount]),Table1[Category]="CostPrice")
*[Sales Value]:=Calculate(Sum(Table1[Amount]),Table1[Category]="SellingPrice")
Tried this in both Calculated Column and Measure but not giving me required output.
Cost:=
CALCULATE(
SUM( Table1[Amount] )
,Table1[Category] = "CostPrice"
)
Selling:=
CALCULATE(
SUM( Table1[Amount] )
,Table1[Category] = "SellingPrice"
)
Profit:=
DIVIDE(
[Selling] - [Cost]
,[Selling]
)
ConditionalMeasure:=
IF(
HASONEFILTER( Table2[Category] )
,SWITCH(
VALUES( Table2[Category] )
,"CostPrice"
,[Cost]
,"SellingPrice"
,[Selling]
,"Profit"
,[Profit]
)
,[Profit]
)
HASONEFILTER() checks that there is filter context on the named field and that the filter context includes only a single distinct value.
This is just a guard to allow our SWITCH() to refer to VALUES( Table2[Category] ). VALUES() returns a table of all distinct values in the named column or table. So, a 1x1 table can be implicitly converted to a scalar, which we need in SWITCH().
SWITCH() is a case statement.
Our else condition in the IF() is just returning [Profit]. You might want something else, but it's unclear what should happen at the grand total level. You can leave this off, and the measure will be blank in IF()'s else condition.
I was thinking about this a little. I'm not sure why you have your categories on rows. Usually the data set would have columns like: item | CostPrice | SellingPrice | Profit. Then you can just use the columns to define your fields. The model becomes easier and more maintainable.

How to have a measure lookup a value based on the row and column context?

I need to Aggregate a number of multiplications which are based on the Row and Columns context. My best attempt at describing this is in pseudo-code.
For each cell in the Pivot table
SUM
Foreach ORU
Percent= Look up the multiplier for that ORU associated with the Column
SUMofValue = Add all of the Values associated with that Column/Row combination
Multiply Percent * SUMofValue
I tried a number of ways over the last few days and looked at loads of examples but am missing something.
Specifically, What won't work is:
CALCULATE(SUM(ORUBUMGR[Percent]), ORUMAP)*CALCULATE(SUM(Charges[Value]), ORUMAP)
because you're doing a sum of all the Percentages instead of the sum of the Percentages which are only associated with MGR (i.e., the column context)
Link to XLS
One way of doing that is by using nested SUMX. Add this measure to ORUBUMGR:
ValuexPercent :=
SUMX (
ORUBUMGR,
[PERCENT]
* (
SUMX (
FILTER ( CHARGES, CHARGES[ORU] = ORUBUMGR[ORU] ),
[Value]
)
)
)
For each row in ORUBUMGR you will multiply percent by ....
the sum of value for each row in Charges where ORUBUMGR ORU is the same as Charges ORU. Then you sum that product.

Resources