New Column is Doubling Value Based on Nested If Formula - powerbi

I have a table that looks like this. Table Screenshot
"FY 20-21 (Budgeted)", "FY21 Approved Budget" and "Revised Budget" are columns coming from three different data sources that I appended into one table. There isn't always data in all three of these columns, so I created a new column to consolidate the data with the following formula:
FY 20-21 Budget =
if(
and(
isblank('Comprehensive Budget'[FY 20-21 (Budgeted)]),
isblank('Comprehensive Budget'[FY21 Approved Budget])
),
'Comprehensive Budget'[Revised Budget],
if(
and(
isblank('Comprehensive Budget'[FY21 Approved Budget]),
isblank('Comprehensive Budget'[Revised Budget])
),
'Comprehensive Budget'[FY 20-21 (Budgeted)],
'Comprehensive Budget'[Revised Budget]
)
)
If both Budgeted and Approved are blank, use Revised.
If not, if both Revised and Approved are blank, use Budgeted.
If not, use Revised.
But if you look on the screenshot, if NONE of the columns are blank, it gives me Revised plus Budgeted. Where is the problem in my formula?

I have added your data here and found your Measure is perfectly returning your expected data as shown in the below image-
I Guess, there are some Aggregation issue in your case. You can right click on all column in the table visual properties and select Don't Summarize from the options. This should solve your issue I hope.

Related

Measure or column filtered by a relationship and a slicer

I have a table Deals which has columns [DealId], [Open Date Id], [Closed Date Id] where the last 2 columns are like a foreign key to the Date table which has [Date], [DateId] column.
Power BI won't let me have 2 active relationship, so one is inactive.
Now I want to create some visuals indicating the deals that were open and closed in a custom range of time (using slicer).
How I tried to solve
The closest solution to this was creating a calculated column with the LOOKUPVALUE and adding the close and open dates directly to Deals table. And created 2 different pages with 2 different slicers, but this is far not the solution I wanted.
How can I solve this problem?
I don't know if what I'm going to say suits your needs based on the size of the tables or the rigidity of the data model due to other measures. I think that in the end what matters is to understand what are the limitations of what you want to show. However, something almost similar I answered here: https://stackoverflow.com/a/66792957/15460989
From what I could understand you have two tables similar to:
Deals = {[DealID] [OpenDate] [CloseDate] [Quantity] [Price] ...}
Dates = {[Date] [MonthName] [MonthNumber] [Year] ...}
And you want to filter Deals based on two relationships
USERELATIONSHIP (Dates [Date], Deals [OpenDate])
USERELATIONSHIP (Dates [Date], Deals [CloseDate])
I am not going to discuss the option of duplicating Dates Table because it was previously covered using two slicers.
But what if the characteristics of my model allow me to use a table with two relationship (One active and the other inactive) while my visualization uses the content of an unrelated table?
Let's define my new unrelated table as:
HarvestingDates = {[Date] [MonthName] [MonthNumber] [Year] ...}
and what I'm trying to achieve is something like this:
From a model like this one:
Deals[DealID]: Unique values.
Deals[OpenDate]: Repeated and missing dates
Deals[CloseDate]: A random number between 0 and 5 is added to Deals [OpenDate]
Instead of choosing an opening date and a closing date, I choose a date range not related to the model and the context related to the deals comes from the measures. Example:
Opened Deals: All the deals opened in a certain date range and summarized by the visualization.
HOpenedDeals: =
CALCULATE(
COUNTROWS(Deals),
TREATAS(
VALUES(HarvestingDate[Date]),Dates[Date]
)
)
Closed Deals: All the deals closed in a certain date range and summarized by the visualization.
HClosedDeals:=
CALCULATE(
COUNTROWS(Deals),
USERELATIONSHIP(Dates[Date],Deals[CloseDate]),
TREATAS(VALUES(HarvestingDate[Date]),Dates[Date])
)
Open and closed deals: All open and closed deals in the same date range summarized by the visualization
HOpened&Closed :=
VAR TotalRow= SUMMARIZE(HarvestingDate,HarvestingDate[Year],HarvestingDate[MonthName])
VAR CurrentDates=VALUES(HarvestingDate[Date])
VAR Result=
ADDCOLUMNS(TotalRow, "Count",
VAR CurrentMonthName= {CALCULATE(VALUES(HarvestingDate[MonthName]))}
VAR CurrentYear= {CALCULATE(VALUES(HarvestingDate[Year]))}
RETURN
COUNTROWS(INTERSECT(
CALCULATETABLE(Deals,
USERELATIONSHIP(Dates[Date],Deals[CloseDate]),
TREATAS(CurrentMonthName, Dates[MonthName]),
TREATAS(CurrentYear, Dates[Year]),
TREATAS(CurrentDates, Dates[Date])
),
CALCULATETABLE(Deals,
TREATAS(CurrentMonthName, Dates[MonthName]),
TREATAS(CurrentYear, Dates[Year]),
TREATAS(CurrentDates, Dates[Date])
)
)))
RETURN SUMX(Result,[Count])
Opened & Not Closed Deals: All open and non-closed deals in the same date range summarized by visualization
HO&NOTC :=
VAR TotalRow= SUMMARIZE(HarvestingDate,HarvestingDate[Year],HarvestingDate[MonthName])
VAR CurrentDates=VALUES(HarvestingDate[Date])
VAR Result=
ADDCOLUMNS(TotalRow, "Count",
VAR CurrentMonthName= {CALCULATE(VALUES(HarvestingDate[MonthName]))}
VAR CurrentYear= {CALCULATE(VALUES(HarvestingDate[Year]))}
RETURN
COUNTROWS(EXCEPT(
CALCULATETABLE(Deals,
TREATAS(CurrentMonthName, Dates[MonthName]),
TREATAS(CurrentYear, Dates[Year]),
TREATAS(CurrentDates, Dates[Date])
),
CALCULATETABLE(Deals,
USERELATIONSHIP(Dates[Date],Deals[CloseDate]),
TREATAS(CurrentMonthName, Dates[MonthName]),
TREATAS(CurrentYear, Dates[Year]),
TREATAS(CurrentDates, Dates[Date])
)
)))
RETURN SUMX(Result,[Count])
TEST
Date range: {5/27/2021…5/31/2021}
I am sure this can be improved but as I said at the beginning it is just an idea. Cheers!
In this case the easiest way is to implement a role playing dimension functionality by duplicating your date table. Power BI engine does not support role playing dimensions, so the workaround for small tables is just duplicating them, as described in this article.
In your case, you could create a table "Date_for_closed" using
Date_for_closed = ALL('Date')
This creates a copy of your original Date table. Then you can create relationships and only have active ones. This way it is even easier to maintain than a bunch of inactive relationships.
With this implemented you can build this:
from this source:

Power BI why circular dependency is detected

Can you please explain why I run into this alert message of circular dependency when I try to create relationship between dimension #product (or #region) and a #bridge table which is a Cartesian of product x region?
I have connected #bridge with Sales and Budget by single column P#G witch is concatenation of product and region.
Download file here: PBIX
The solution is simple. Do not use CALCULATE function in the DAX bridge tables. Instead add all that columns to the same table later as calculated columns.
I changed the original code of the bridge table which was:
ADDCOLUMNS (
CROSSJOIN ( '#product', '#region' ),
"P#R", COMBINEVALUES("#",'#product'[product], '#region'[region]),
"sales", CALCULATE ( SUM ( Budget[target] ) ),
"IsSale", IF ( CALCULATE ( SUM ( Budget[target] ) ) > 0, "Yes", "No" )
)
To something simpler:
ADDCOLUMNS (
CROSSJOIN ( '#prodact', '#region' ),
"P#R", COMBINEVALUES("#",'#prodact'[product], '#region'[region])
)
I modified the DAX code of bridge table so as to leaving only the columns necessary for joins. The columns that I needed to be calculated I added as calculated columns. And that's it. It was by pure chance I found that out while experimenting with it.
For playing with bridge tables I recommend this Alberto Ferrari's article: https://www.sqlbi.com/articles/avoiding-circular-dependency-errors-in-dax/. It inspired me to solve the problem. What I get from the Alberto's text is that the functions VALUES and ALL are no good for bridge tables. He mentions issue of using CALCULATE function inside the bridge DAX tables. The function somehow is translated to mixture of ALL and FILTER functions. Instead of VALUE and ALL, use functions as DINSTINCT and ALLNOBLANKROW.
Working PBIX file. Hurray!
A quick and dirty solution is to creat to new versions of #product and #region by using VALUES. This is probably not the best way of doing it...
NewProduct = VALUES('#product'[product])
This new tables can be linked to #bridge with a 1:* relationship and thus can be used as a slicer on the dashboard.
Alberto has written about this on the sqlbi blog: Circular dependency sqlbi blog

Filtering other tables based on cross-highlighting a filtered measure

I want to count records in a certain condition and allow people to filter down to the relevant records, but selecting a measure value (which filters so it only counts certain rows) isn't cross-filtering others as I'd expect. Maybe ths isn't possible or maybe I'm just doing it wrong, but I'd appreciate help.
I have a single table:
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45Wci4tLsnPTS1SMFTSUTJUitVBEjICChmgChljCplgajSFCMUCAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [#"Customer Name" = _t, #"Ordered Recently" = _t]),
#"Change to INT" = Table.TransformColumnTypes(Source,{{"Ordered Recently", Int64.Type}}),
#"Change to T/F" = Table.TransformColumnTypes(#"Change to INT",{{"Ordered Recently", type logical}})
in
#"Change to T/F"
The result looks like this:
Customer Name Ordered Recently
Customer 1 True
Customer 2 False
Customer 3 False
Customer 4 True
Customer 5 True
I added two measures:
Count Total = COUNTROWS(Customers)
Count Recent = CALCULATE([Count Total], filter(Customers, Customers[Ordered Recently]))
If I put both measures in a bar chart and highlight the "Count Recent" measure, I'd expect it to know to filter other visuals based on the FILTER statement present in the measure, but that doesn't happen. Selecing this value doesn't impact anything else on my page (including just a count of rows).
The goal is to allow people to select a measure that counts rows and then to see the makeup of the data in those rows (select a count of late projects and filter other visuals to describe those late projects).
Is this possible or am I doing something wrong?
EXAMPLE:
Here's what it looks like now, with nothing selected:
When I select the black bar (the "Ordered Recently" measure), nothing changes right now - but here's what I want to happen (actually achieved with a slicer off screen on the T/F field):
I understand if my measure is a SUM of an integer field, it includes every row in the calculation - even when the row value is zero - and there's no way to filter my dataset based on that. However, in this case, my measure is actually using a FILTER on the dataset so that it only counts rows with a certain criteria set - given that, it should be able to filter the requested table, and then flow that filter through the rest of my dataset (the same way it would if I selected a bar from a chart where I had used that same field as the series - exactly how it works when I do this:
PBIX file to download as an example
No, I don't believe it's possible to make a measure value cross-filter other visuals based on filters within the measure definition.
You can, however, click on i.e. row header Customer 3 and it should cross-filter the other visuals to only include that customer. Any table column you set for the rows or columns of a matrix visual should behave this way.
Here's a hacky workaround:
Create a measure that shows the right values when you use the column you want to use as a filter as the Legend or Axis (like in your last image). For example, in this case, you could do this:
Total Customers =
VAR TF = SELECTEDVALUE ( Customers[Ordered Recently] )
RETURN
COUNTROWS (
FILTER (
ALLSELECTED ( Customers ),
IF ( TF, TF, TF || Customers[Ordered Recently] )
)
)
This behaves how you want, but isn't labeled as you want. To achieve that create a calculated column with the labels you want. For example,
Label = IF(Customers[Ordered Recently], "Ordered Recently", "Total Customers")
Then take Ordered Recently off the axis and put the Label column in the Legend box to get this:
Your Filter argument is really Filter(All(Customers, Customers[Ordered Recently])
You remove all filters on the Customer Table, and then specify Ordered Recently Column as the filter.
Try
[MeasureName] =Calculate([Count Total], All(Customer), Values(Customer[Recently Ordered]), Customer[Recently Ordered] = “True”)

Inactive relationships affecting measures

I have the following tables & relationships in our pbix report:
For some obvious reasons, I need to have a relationship (non-active) between Dates[date] and Table2[T2Date]. However, doing so causes data fluctuation to measure 'Total Amount' in Table1.
Here are some screenshots:
Before Relationship (Dates[date] - Table2[T2Date]):
After Relationship (Dates[date] - Table2[T2Date]):
I need to understand why this difference is coming up and how the relationship is causing it since the measure uses a different relationship.
For reference, I am attaching the pbix report.
https://drive.google.com/open?id=1XknisXvElS6uQN224bEcZ_biX7m-4el4
Any help would be appreciated :)
The link that #MikeHoney gives has really useful information on the subtleties of relationships and does relate to this problem (do watch it!), but this issue is not ultimately related to bidirectional filtering in particular. In fact, I can reproduce it with this simplified relationship structure:
The key thing to note here is that when you attach Table2 to Dates, since Table2 contains T2Date values that don't match to any Date[date], this creates an extra row in Dates with a blank date which you can notice in your filter on 6. Year when that relationship exists (active or inactive). Filtering out that that blank in the 6. Year filter would work, except that in your measure, you use ALL(Dates) to strip all filtering done on that table.
There are multiple ways to resolve this discrepancy, the easiest being replacing ALL with ALLNOBLANKROW. If you used ALLSELECTED that would also work in conjunction with filtering out blanks on your report-level filter on 6. Year.
Cleaning up some items not relevant in this context and changing ALL to ALLNOBLANKROW, your total measure can be more simply written as:
ALLNOBLANKROW =
VAR EndServiceDate =
MAX ( Dates[Date] )
RETURN
CALCULATE (
SUM ( Table1[Net Amount] ),
FILTER (
ALLNOBLANKROW ( Dates ),
Dates[Date] <= EndServiceDate
),
Table1[Flag2] = 1,
Table1[Flag] = TRUE ()
)
Results with no 6. Year filter and with two measures, one using ALL and one using ALLNOBLANKROW:
Notice that every row in the ALL column has been reduced by -7,872.01. This is the sum of all the Net Amount values that don't match to any dates in the Dates table. If you remove the relationship from Dates[date] to Table2[T2Date] then the blank row no longer exists and both of these will match the ALLNOBLANKROW version.
Setting the Cross Filter Direction to Both on any relationship is a bit risky - you essentially hand over control of the runtime query designs to the Power BI robots. There's then a risk that they will come up with a "creative" query design that is unexpected.
There's some insight into how this happens in a recent talk by Alberto Ferrari:
https://www.sqlbi.com/tv/understanding-relationships-in-power-bi/
I'm sure you'll agree it's quite terrifying.
Looking at your info, I expect you can avoid those traps by changing the Cross Filter Direction to Single, for the relationship from MonthYear to Dates.

Trying to Reorder Columns in Data View in Power BI

Is there a way I can reorder columns in 'Data View' within Power BI? I tried doing it in Power Query first but when the data loads into the table, the columns automatically rearrange.
Edit after comment.
There is easy fix to enforce column order just as in Power Query:
In Power Query Editor > Disable Query Load. Close and Apply.
Open the Query Editor again, enable the Query Load. Refresh the Query. Then Close and Apply.
Answer to misunderstood question.
This may be interesting solution in M PowerQuery. The function below let you reorder columns by only stating few columns from the whole set of columns. Add this in blank query and rename it to FnReorderColumnsSubset.
(tbl as table, reorderedColumns as list, offset as number) as table =>
Table.ReorderColumns
(
tbl,
List.InsertRange
(
List.Difference
(
Table.ColumnNames(tbl),
reorderedColumns
),
offset,
reorderedColumns
)
)
Use it as this:
= FnReorderColumnsSubset( Source, { "Region", "RegionManager", "HeadCount" }, 0 )
Found it here:
https://datachant.com/2017/01/18/power-bi-pitfall-4/
It is extremely stupid way, but it is working - i found it by accident:
In edit query view remove the column, then save changes. You will see that in data view that column was removed as well.
Now again in edit query view remove from applied steps the action that removed the column. Save it again.
You will see that removed previously column was added to the end of the table.
This way you can arrange your columns to have it the way you want it in data view.
Hope it helped.
I don't know that you can rearrange an existing table, but if you re-create it as a new table, you can pick the order you want.
NewTable =
SELECTCOLUMNS (
OldTable,
"Column1", OldTable[Column1],
"Column2", OldTable[Column2],
"Column3", OldTable[Column3]
)
I think most here have misunderstood the problem, except #Jacko. So far as I know it is now possible to re-arrange columns in Power Query and load to the model and the table will load in the column order you specified in PQ. The problem is in dataview in the modelling layer of PBi. Here you can add many calculated columns, but, any new column you add is always placed at far right and can't be moved. Yes, I know about SELECTCOLUMNS but it isn't a solution as the new table does not have the editable formulae. A solution is a drag and drop feature of some sort. PBi users are still waiting for it despite the problem being flagged in MS Forums some years ago. No progress TIKO other than the limp SELECTCOLUMNS solution.