Circular Dependency in DAX calculated column::AAS model - dax

I am stuck in the situation where I am adding a new calculated column but it's prompting me the circular dependency. The first column is calculated like:
=VAR Denominator = ( Validation_Accounts_Agreements[CalculatedClosedDateVsFirstPurchaseDate] + 1 )
VAR Sales =
CALCULATE (
SUM ( SalesR48NBVBySolution[TotalSales] ),
FILTER (
SalesR48NBVBySolution,
SalesR48NBVBySolution[invoicedate] >= Validation_Accounts_Agreements[CalculatedFirstAnchorPurchaseDateAfterGTWClosedDate]
)
)
VAR R6AnchorSales =
CALCULATE (
SUM ( SalesR48NBVBySolution[TotalSales] ),
FILTER (
SalesR48NBVBySolution,
SalesR48NBVBySolution[invoicedate]
>= EDATE (
Validation_Accounts_Agreements[CalculatedFirstAnchorPurchaseDateAfterGTWClosedDate],
-6
)
&& SalesR48NBVBySolution[invoicedate] < Validation_Accounts_Agreements[CalculatedFirstAnchorPurchaseDateAfterGTWClosedDate]
&& SalesR48NBVBySolution[ClensedAnchorDesignation] = "Y"
)
)
RETURN
IF ( ISBLANK ( R6AnchorSales ),
IF ( NOT (ISBLANK ( Validation_Accounts_Agreements[CalculatedFirstAnchorPurchaseDateAfterGTWClosedDate] )
)
&& ISBLANK ( R6AnchorSales ),
DIVIDE ( Sales, Denominator ) * 12
)
)
The next column I want to create here is:
=VAR Denominator = ( Validation_Accounts_Agreements[CalculatedClosedDateVsFirstPurchaseDate_SLN] + 1 )
VAR Sales =
CALCULATE (
SUM ( SalesR48NBVBySolution[TotalSales] ),
FILTER (
SalesR48NBVBySolution,
SalesR48NBVBySolution[invoicedate] >= Validation_Accounts_Agreements[CalculatedFirstPurchasedateAfterGTWClosedDate_SLN]
)
)
VAR R6AnchorSales =
CALCULATE (
SUM ( SalesR48NBVBySolution[TotalSales] ),
FILTER (
SalesR48NBVBySolution,
SalesR48NBVBySolution[invoicedate]
>= EDATE (
Validation_Accounts_Agreements[CalculatedFirstPurchasedateAfterGTWClosedDate_SLN],
-6
)
&& SalesR48NBVBySolution[invoicedate] < Validation_Accounts_Agreements[CalculatedFirstPurchasedateAfterGTWClosedDate_SLN]
&& SalesR48NBVBySolution[ClensedAnchorDesignation] = "N" && CALCULATE(MAX('CAM Alignment'[NodeCd_L3])=="C3-10-00015")
)
)
RETURN
IF ( ISBLANK ( R6AnchorSales ),
IF ( NOT (ISBLANK ( Validation_Accounts_Agreements[CalculatedFirstPurchasedateAfterGTWClosedDate_SLN] )
)
&& ISBLANK ( R6AnchorSales ),
DIVIDE ( Sales, Denominator ) * 12
)
)
Here is more info about my model::
In the above picture, the yellow highlighted columns I am using to create the calculated column 1 (calculated Annualization).The red circled columns are being used to create column 2 ( calculated Annualization_SLN).both sets of columns are almost similar (changes in the filter).But when I am trying to create column 2 ( calculated Annualization_SLN) that time I am getting this error of circular dependency; which is dependent on column 1.

In general, according to best-practice avoid extensively using Calculated Columns. Instead, add them in your data source (back-end) or use M-Query.
In order to answer your question precisely, you need to share more information about your model (i.e. relationships). However, we can provide you some guidelines referring to this article in order to avoid circular dependencies.
Quoting the conclusion of the article:
Most of the time, circular dependencies occur when you use calculated tables. You can easily avoid them by paying attention to your choice of functions. The difference between DISTINCT and VALUES, or between ALL and ALLNOBLANKROW is a subtle difference. But once you get used to it, your code will be safer when it comes to relationships and circular references.

Related

Power Bi: how to parameterize Top N visual level filter [duplicate]

This question already has answers here:
Power Bi: Top N visual level filter as Measure
(2 answers)
Closed 6 months ago.
Since PowerBI don't support Top N filter on page level,
I want to use N as a parameter to change it at once per multiple visuals.
Is it possible?
P.S.In this video (9:15) solution for more complex case is provided.
In the end of this article sample file available
Using the sample dataset, insert a new parameter.
Add a measure as follows:
Measure =
IF(
SELECTEDVALUE('Product'[Product Name]) IN
SELECTCOLUMNS(
TOPN(
[Parameter Value],
ADDCOLUMNS( ALLSELECTED( 'Product'),"#Sales", [Sales Amount] ),
[#Sales]
),
"x",
'Product'[Product Name]),
1)
Every visual you want affected by the TopN should have this filter.
That's it.
From usability perspective it's preferable to return Sales Rank in measure.
Solution below is a copy/paste from SQLBI experts solution with minimal code changes ( ALLSELECTED ( 'Product'[Product Name] ) replaced by ALLSELECTED ( 'Product' ) ):
rnkSales =
IF (
ISINSCOPE ( 'Product'[Product Name] ),
VAR ProductsToRank = [TopN Value]
VAR SalesAmount = [Sales Amount]
RETURN
IF (
SalesAmount > 0,
VAR VisibleProducts =
FILTER( -- filters out data with no sales
CALCULATETABLE (
VALUES ( 'Product' ),
ALLSELECTED ( 'Product') -- Use this if VisualFilterTopN equivalent required
//ALLSELECTED ( 'Product'[Product Name] ) -- Original code - returns TopN per dimension
),
NOT ISBLANK( [Sales Amount] ) -- looks more universal then [Sales Amount]>0 (if calculation for Margin required, it could be negative)
)
VAR Ranking =
RANKX (
VisibleProducts,
[Sales Amount],
SalesAmount
)
RETURN
IF (
Ranking > 0 && Ranking <= ProductsToRank,
Ranking
)
)
)

Summing up values

A tabular model.
The table 'Historic Project One Hour Value' contains hours value (like price) for working hours on projects on several dates.
It is connected only to the project table but not to the date table .
I'm trying to calculate the hours value. For my question let's say there is only one hour on each project.
I get the correct answer for each project, but the total is a very big number, which I don't understand.
I will appreciate your help.
One Hour Value On Date :=
VAR OneHourValueOnStartDate =
FILTER (
'Historic Project One Hour Value',
'Historic Project One Hour Value'[HistoricOneHourValueBeginDate]
= DATE ( 2016, 12, 31 )
)
VAR OneHourValueOnStartDateForOneProject =
1
* /*Actually, I multiply the working hours of the project, but this number is correct */
CALCULATE (
SUM ( 'Historic Project One Hour Value'[HistoricOneHourValue] ),
OneHourValueOnStartDate
)
RETURN
IF (
HASONEVALUE ( Projects[Project ID] ),
CALCULATE ( OneHourValueOnStartDateForOneProject ),
CALCULATE (
SUMX ( VALUES ( Hours[HoursProjectID] ), OneHourValueOnStartDateForOneProject )
)
)
The variable OneHourValueOnStartDateForOneProject is a constant (not a measure), so what's happening in your total is that this value gives you the sum for all Project ID values in the VAR calculation part.
From there, your SUMX adds that constant value the same number of times as there are distinct HoursProjectID.
The correct code after Alexis Olson answer:
One Hour Value On Date:=
VAR OneHourValueOnStartDate =
FILTER (
'Historic Project One Hour Value',
'Historic Project One Hour Value'[HistoricOneHourValueBeginDate]
= date(2016,12,31)
)
VAR OneHourValueOnStartDateForOneProject =
1 * /*Actually, I multiply the working hours of the project, but this number is correct */
CALCULATE (
SUM( 'Historic Project One Hour Value'[HistoricOneHourValue] ),
OneHourValueOnStartDate
)
RETURN
IF (
HASONEVALUE ( Projects[Project ID] ),
CALCULATE ( OneHourValueOnStartDateForOneProject ),
CALCULATE (
SUMX (
Values ( Hours[HoursProjectID] ),
1
* CALCULATE (
MAX ( 'Historic Project One Hour Value'[HistoricOneHourValue] ),
FILTER (
OneHourValueOnStartDate,
'Historic Project One Hour Value'[HistoricOneHourValueProjectID]
= EARLIER ( 'Hours'[HoursProjectID] )
)
)
)
)
)
Thank you

Count how many sub-activities were created based on an activity

I have a dimension that stores workflows(cases, subcases). I would like to do a count of how many subcases are created for each case.
Workflow Dimension
Workflow
------------------------------
Case Number WorkflowType
------------------------------
10 Case
20 Case
30 Case
20-1 Subcase
20-2 Subcase
20-3 Subcase
10-1 Subcase
The desire output I would like is, for every case count how many subcases were created.
Workflow
------------------------------------------------
Case Number WorkflowType CountOfSubcases
------------------------------------------------
10 Case 1
20 Case 3
30 Case 0
------------------------------------------------
Total 4
I have a current dax measure that works, but the total at the bottom does not show when looking at multiple rows, only display when one case is selected.
Total Subcases =
VAR CC = FIRSTNONBLANK ( Workflow[Case Number], 1 )
RETURN
COUNTX (
FILTER (
ALL( Workflow ),
SUBSTITUTE ( Workflow[Case Number], RIGHT ( Workflow[Case Number], 2
), "" )
= CC
&& Workflow[WorkflowType] = "SubCase"
),
Workflow[WorkflowID]
)
If anybody could help me tweak my measure or present with a new measure, that would be great.
Note: I'm pointing my report to Analysis Services.
Thanks in advance.
You can fix your measure as follows:
Total Subcases = 0 +
COUNTX (
FILTER (
ALL( Workflow ),
SUBSTITUTE ( Workflow[Case Number], RIGHT ( Workflow[Case Number], 2 ), "" )
IN VALUES( Workflow[Case Number] )
&& Workflow[WorkflowType] = "SubCase"
),
Workflow[WorkflowID]
)
The VALUES function returns a list of all the values in the current filter context instead of just the one you were picking before.
Note: To make things easier to work with, I'd suggest splitting the Case Number column into two columns in the query editor stage. Then you don't have to work with all the string manipulation.
Edit: Note that x IN <Table[column]> is equivalent to the older CONTAINS syntax:
CONTAINS(Table, [column], x)
So if you can't use IN then try this formulation:
Total Subcases = 0 +
COUNTX (
FILTER (
ALL( Workflow ),
CONTAINS(
VALUES( Workflow[Case Number] ),
Workflow[Case Number],
SUBSTITUTE ( Workflow[Case Number],
RIGHT ( Workflow[Case Number], 2 ), "" )
)
&& Workflow[WorkflowType] = "SubCase"
),
Workflow[WorkflowID]
)

Calculating payback period using DAX

I'm working on some calculations for capital budgeting, and I have the following two tables in my data model
I'm trying to build out a calculated column in DAX to determine the payback period for each project in the Project table. I've put together the calculation here, I'm just not sure exactly how to execute this in DAX.
Logical Steps for Calculating Payback Period:
For each Project, find the cumulative sum for each date for relevant metrics (Include OpEx Savings and OpEx Implementation Cost, but not Revenue or Working Capital)
Find the MIN date where cumulative sum is greater than zero (the "break-even" date")
Find the MIN date with non-zero implementation cost ("Investment date")
Find the difference (in months) between #2 and #3 to determine payback period
EDIT:
The answer for the listed project is 7 months. I've built an intermediate table in Excel to develop the answer, but I'd like to be able to do this directly in a PowerPivot table with DAX.
I've produced this as a solution:
Create values, which makes sure cost are - and savings are + (ValCorr)
Create a running sum (RunningSum)
Find Investment Date (InvestmentDate)
Find Breakeven Date (BreakEvenDate)
Find Difference (Payback)
DAX:
RunningSum =
CALCULATE(SUM(Impacts[ValCorr]);
FILTER(
ALL(Impacts);
Impacts[ProjectID] = EARLIER(Impacts[ProjectID]) &&
Impacts[Date] <= EARLIER(Impacts[Date])
))
InvestmentDate =
CALCULATE (
FIRSTNONBLANK ( Impacts[Date]; 0 );
FILTER ( ALL ( Impacts ); Impacts[RunningSum] <> 0 )
)
BreakEvenDate =
CALCULATE (
FIRSTNONBLANK ( Impacts[Date]; 0 );
FILTER ( ALL ( Impacts ); Impacts[RunningSum] > 0 )
)
Payback = DATEDIFF(Impacts[InvestmentDate];Impacts[BreakEvenDate];MONTH)
Result:
Good luck!
After a fair amount of trial and error, I came up with a solution.
Step 1: Build out a helper metrics table. This serves 2 purposes: (a) excludes irrelevant metrics (like revenue), and (b) ensure costs are negative and savings are positive.
Metrics Table
Step 2: Build 2 helper measures that will go into the virtual, summarized, intermediate table.
CumulativeTotalMetric :=
CALCULATE (
SUMX (
Impact,
Impact[Latest Estimate Monthly Values]
* RELATED ( BaseMetrics[Payback Period Multiplier] )
),
FILTER ( ALL ( Impact[Month] ), Impact[Month] <= MAX ( Impact[Month] ) )
)
TotalMetric :=
SUMX (
Impact,
Impact[Latest Estimate Monthly Values]
* RELATED ( BaseMetrics[Payback Period Multiplier] )
)
Step 3: Create the final measure that creates the virtual table (BaseTable), and performs logical operations on it to arrive at the final payback period.
Payback Period (Years) :=
VAR BaseTable =
ADDCOLUMNS (
SUMMARIZE ( Impact, Impact[initiative #], Impact[snapshot], Impact[Month] ),
"Cumulative Total Impact", CALCULATE ( [CumulativeTotalMetric] ),
"Total Impact", CALCULATE ( [TotalMetric] )
)
VAR LastCumulativeLossDate =
MAXX ( FILTER ( BaseTable, [Cumulative Total Impact] < 0 ), [Month] )
VAR BreakEvenDate =
MINX (
FILTER (
BaseTable,
[Month] > LastCumulativeLossDate
&& [Cumulative Total Impact] > 0
),
[Month]
)
VAR InitialInvestmentDate =
MINX ( FILTER ( BaseTable, [Total Impact] < 0 ), [Month] )
RETURN
IF (
OR ( ISBLANK ( InitialInvestmentDate ), ISBLANK ( BreakEvenDate ) ),
BLANK (),
( BreakEvenDate - InitialInvestmentDate )
/ 365
)
This last meaure is pretty complicated. It uses progressive, dependent variables. It starts with the same base table, and defines variables that are used in subsequent variables. I'm no DAX expert, but I suspect using these variables helps with the calculation efficiency.
EDIT: I should note that I didn't use this measure as a calculated column -- I simply used it in a pivot table which is the same "shape" as the "Projects" table above -- one line per project / initiative.

Measure that should summarize sales for parent company regardless of child company filter

I have a table with SalesCompanies. The table contains one column ChildCompany and another column ParentCompany.
How can I make the measure below aggregate per ParentCompany regardless of ChildCompany filtering?
CustomerSalesSinceLastInventory:=CALCULATE(
SUM(factCustomerSales[Quantity])
;FILTER(
ALL(dimCalendar[Date])
;dimCalendar[Date] >= MIN(parCurrentMonth[Date])
&& dimCalendar[Date] <= MAX(dimCalendar[Date])
)
)
This is one way of achieving the desired result:
CustomerSalesSinceLastInventory :=
SUMX (
ADDCOLUMNS (
VALUES ( 'dimSalesCompanies'[ParentCompany] );
"Total sales"; CALCULATE (
SUM ( [Quantity] );
ALL ( 'dimSalesCompanies'[Company] );
FILTER (
ALL ( dimCalendar[Date] );
dimCalendar[Date] >= MIN ( parCurrentMonth[Date] )
&& dimCalendar[Date] <= MAX ( dimCalendar[Date] )
)
)
);
[Total sales]
)
This measure adds a column(in memory, you will not actually see it) which groups/aggregates the sale per ParentCompany. The time filter is also included in this column.

Resources