Calculated column that ignores row context - dax

I'm trying to calculate the Total Price per Order number. It specifically needs to be a column, because I'll be needing it for further calculations.
Can someone help me write code that calculates the total per Order Number, instead of line amount as it does now?

Since it's a calcualted column, just avoiding any context transition gives a straightforward solution
Total Price Per Order =
VAR CurrentOrder = SalesDetail[Order Number]
RETURN
SUMX (
FILTER (
SalesDetail,
SalesDetail[Order Number] = CurrentOrder
),
SalesDetail[Unit Price] * SalesDetail[Quantity]
)

Related

DAX: Unwanted cartesian product lines?

Please help to calculate/understand properly lastDate and rankDate measures for following simplified example (download):
Desired result:
Reality (incorrect subtypes):
Why relationship is broken?
How to avoid this cartesian product lines?
My Measure (I commented workaround, because it's kind of postfilter, not prefilter):
rnkDate =
VAR t =
CALCULATETABLE(
VALUES(tstTable[Date]),
REMOVEFILTERS(tstTable[Date])
)
RETURN
//IF( MAX(tstTable[Amount])<>BLANK(), // WORKAROUND To hide unwantedd rows
RANKX(
t,
LASTDATE(tstTable[Date])
)
//)
P.S. Mess happens only if I use fields from dimensional table dimType[Type] (within one table everything is Ok):
The problem is that the query generated by Power BI performs the cartesian product and filers the result by checking the result of the measure.
in our case is something similar to
SUMMARIZECOLUMNS(
'dimType'[Type],
'tstTable'[subType],
'tstTable'[Date],
"MinAmount", CALCULATE(MIN('tstTable'[Amount])),
"lastDate", 'tstTable'[lastDate],
"rnkDate", 'tstTable'[rnkDate]
)
SUMMARIZECOLUMNS doesn't use relationships when iterating on different tables, it applies them when evaluating the measures. There is an article explaining what is the equivalent DAX code executed by SUMMARIZECOLUMNS
Introducing SUMMARIZECOLUMNS
the problem is that RANKX evaluated on an empty table retuns 1. This can be seen executing this on dax.do
EVALUATE
VAR t =
FILTER ( ALL ( 'Date'[Date] ), FALSE )
RETURN
{ RANKX ( t, [Sales Amount] ), CALCULATE ( [Sales Amount], t ) }
so the solution is to first check that the table t is not empty, which is the reason because the workaround that you implemented solved the issue
lastDate =
IF( NOT ISEMPTY(tstTable), // checks fact table in particular context
CALCULATE(
LASTDATE(tstTable[Date]),
REMOVEFILTERS(tstTable[Date])
)
)
rnkDate =
VAR t =
CALCULATETABLE(
VALUES(tstTable[Date]),
REMOVEFILTERS(tstTable[Date])
)
RETURN
IF( NOT ISEMPTY(tstTable),
RANKX(
t,
LASTDATE(tstTable[Date])
)
)

Dax Power Pivot Cumulative Total Over Development Period Dimension

I'm new to Dax and I'm struggling to get the results I require with a running total.
I hope I've give you enough information below to help..
thank for any help and pointer in advance.
I'm trying to create an insurance triangle, I have 3 tables fact_transaction_claims_payments, dimension_development_Periods and reporting_upto_information
fact_transaction_claims_payments
dimension_development_Periods
reporting_upto_information
diagram view
I've managed to get my running total to work but only where there is a development period held in the fact table and not all the ones in between held in my development period dimension
Power Pivot Running Total
for example i'd expect development period 1 - 10 to total 0.00 and 13 to 18 to total 103,710
but i can seem to get these to appear in my pivot.
Running Total Dax Expression
RT_TotalAmount1:=VAR CurrentDevelopmentPeriod =
CALCULATE(
DATEDIFF(
IF(
MAX('fact_transaction_claims_payments'[cUWYear]) < 2011
, DATE(MAX('fact_transaction_claims_payments'[cUWYear]),1,1)
, DATE(MAX('fact_transaction_claims_payments'[cUWYear]),4,1)
)
,MAX('fact_transaction_claims_payments'[EndOfMonthDate])
,MONTH)
, 'dimension_development_Periods' ) +1
VAR MaxDevelopmentPeriod =
CALCULATE(
DATEDIFF(
IF(
MAX('fact_transaction_claims_payments'[cUWYear]) < 2011
, DATE(MAX('fact_transaction_claims_payments'[cUWYear]),1,1)
, DATE(MAX('fact_transaction_claims_payments'[cUWYear]),4,1)
)
,MAX('reporting_upto_information'[EndOfMonthDate])
,MONTH)
, 'dimension_development_Periods' ) +1
VAR RunningTotal =
CALCULATE (
SUM('fact_transaction_claims_payments'[TotalAmount])
,FILTER (
ALL ('fact_transaction_claims_payments')
,'fact_transaction_claims_payments'[DevelopmentMonthNumber] <= CurrentDevelopmentPeriod
)
)
RETURN
RunningTotal
I've tried adding the ALL('dimension_development_Periods') into the VAR DevelopmentPeriod
but this just puts the grand total against every development period.
I'm thinking I now need to use the RunningTotal to calculate against the Development Period Dimension filtered <= the max development period for the cUWYear but I'm not sure on how to implement this and I need some advice can anyone help.

Overlapping task duration aggregation in DAX Hierarchy

SCENARIO:
Monitor “Task” duration. Purpose is to track trend in changing Durations.
There is a framework that stores information about tasks in place.
There is a hierarchy setup using parent/child ID.
Columns; Task_ID, Parent_Task_ID, Start_Time, End_Time, Duration.
A hierarchy has been set up With Calculated Columns
Depth, Path, Level1-Level4. (according to DAX Patterns on Hierarchy)
Measures; Browsedepth and RowDepth has been set up to remove blanks in the report setup for empty levels.
DAX;
Sum Hierarchy =
VAR Val = [Sum Duration]
VAR ShowRow=[BrowseDepth] <= [RowDepth]
RETURN IF(ShowRow,Val)
CHALLENGE:
In the Task table all durations are correct, so there are no need to aggregate the duration of the children up to parent.
In Daxpatterns connected to hierarchies in the examples I have found, there are always aggregation up from children to parent, as the black numbers in the matrix under are showing
The goal is to find a way to create a measure that avoid aggregation from children to parent, and present the "Blue numbers in the picture above.
Do anyone have any pointers on the pattern or logic to use, it would be greatly appreciated.
Kind regards,
Atle Røen
The answer to this was to use MAX( 'Task'[Duration] ) and filter on the last task execution. Simple when you finally find the answer :D
DAX;
Max Task duration - Last run:=
CALCULATE (
MAX( 'Task'[Duration] ),
LASTDATE ( (
FILTER (
VALUES ( 'Task'[Start_Time] ),
MAX ( 'Calendar'[Date] ) >= 'Task'[Start_Time]
)
) )
)
Task duration - Last run - Hier:=
VAR Val = [Max Task duration - Last run]
VAR ShowRow = [BrowseDepth] <= [MaxNodeDepth]
RETURN IF(ShowRow,Val)

Power Bi - Add Total Average column in Matrix

Hi I am trying to add a AVERAGE column in a matrix, but when I put my metric added the average per column, but I need a total AVERAGE and total at the end just once
What I have:
What I need:
Group
Maria
Pedro
average
total
First
4
6
5
10
Second
5
10
7.5
15
Regards
Following the example detailed in the sample data table, to get the Total you could add the following measure;
Total By Group = CALCULATE( SUM(AverageExample[Maria]) + SUM(AverageExample[Pedro]))
and to average
Average By Group = [Total By Group] / 2
Based on the first three columns, this will provide
You have to build a DAX table (or Power Query) and a designated measure.
Matrix Table =
UNION(
DATATABLE("Detail", STRING, "Detail Order", INTEGER, "Type", STRING, {{"Average", 1000, "Agregate"}, {"Total", 1001, "Agregate"}}),
SUMMARIZE('Your Names Table', 'Your Names Table'[Name], 'Your Names Table'[Name Order], "Type", "Names")
)
This should give you a table with the list of people and 2 more lines for the agregations.
After that, you create a measure using variables and a switch function.
Matrix Measure =
var ft = FIRSTNONBLANK('Matrix Table'[Type], 0)
var fd = FIRSTNONBLANK('Matrix Table'[Detail], 0)
return SWITCH(TRUE,
ft = "Names", CALCULATE([Total], KEEPFILTERS('Your Names Table'[Name] = fd)),
fd = "Total", [Your Total Measure],
fd = "Average", [Your Averagex Measure]
)
The rest is up to you to fiddle with orders, add any agregate measures and whatnot.
Note that the Matrix Table should have no relation with any table from your model.
You can also hide it and the Matrix measure.

DAX IF measure - return fixed value

This should be a very simple requirement. But it seems impossible to implement in DAX.
Data model, User lookup table joined to many "Cards" linked to each user.
I have a measure setup to count rows in CardUser. That is working fine.
<measureA> = count rows in CardUser
I want to create a new measure,
<measureB> = IF(User.boolean = 1,<measureA>, 16)
If User.boolean = 1, I want to return a fixed value of 16. Effectively, bypassing measureA.
I can't simply put User.boolean = 1 in the IF condition, throws an error.
I can modify measureA itself to return 0 if User.boolean = 1
measureA> =
CALCULATE (
COUNTROWS(CardUser),
FILTER ( User.boolean != 1 )
)
This works, but I still can't find a way to return 16 ONLY if User.boolean = 1.
That's easy in DAX, you just need to learn "X" functions (aka "Iterators"):
Measure B =
SUMX( VALUES(User.boolean),
IF(User.Boolean, [Measure A], 16))
VALUES function generates a list of distinct user.boolean values (1, 0 in this case). Then, SUMX iterates this list, and applies IF logic to each record.

Resources