ALLSELECTED not applied on Calculated Column - powerbi

I have two tables as indicated below. The first is a list of dates, the second a list of contracts with their contract start and end dates. The tables are not related since there are two date realtionships. I need to give a summary of how many contracts started and ended on each day. This works fine using a calcualted column, however, when I try and slice on Type or Contract customer, the results in the Date table's calculated columns do not apply, even though ALLSELECTED is applied. How can I get the slicers to filter the rows returned to the to calculated column so that the number of contracts are calculated accordingly.
Calculated column:
StartedContracts = COUNTROWS(FILTER(ALLSELECTED(Contracts), Contracts[StartDate] = DateData[Date]))
Reproduction PBIX here

To get this displaying correctly, an easy way is to go ahead and set up the relationships between the tables. You'll have an active relationship and an inactive relationship, something like this with an active relationship to [StartDate] and an inactive relationship to [EndDate]:
Having done this, defining the measures is simplicity itself!
StartedContracts = COUNTROWS(Contracts)
EndedContracts = CALCULATE(COUNTROWS(Contracts), USERELATIONSHIP(Contracts[EndDate], DateData[Date])
Since the active relationship is to the Contracts[StartDate] column, you don't need to specify any additional filters for StartedContracts.
When calculating EndedContracts you just need to add USERELATIONSHIP() to the CALCULATE() function to tell it to use the inactive relationship which was previously defined to the Contracts[EndDate] column.
Slicers on other columns work as expected.

Related

DAX/Power BI - Filter Two Unrelated Tables

I need to filter a table based on another table, however there is not a direct relationship between the two. Here is the data model.
attr_Tkpr_vw contains all company employees, both current and historical.
attr_Time_vw contains date/time info.
My goal is to filter attr_Tkpr_vw for all employees between arbitrary hire and termination dates. These dates are supplied by a slicer based on the column attr_Time_vw[DateFull]
Here are my results. My slicer is set to dates between 1/1/2022 and 3/31/2022. When I put the measues "MinDate" and "MaxDate" into a vizualization I get the expected results. However, when I try and use these measures to filter attr_Tkpr the formula returns a table with ALL dates.
I'm clearly missing something key about how filter contexts work.
I have tried using the fuctions VALUES, SELECTEDVALUE, ALLSELECTED. None returns expected results.

Power BI / DAX return values from table from rows filtered out by slicer

I have a table visualisation that shows the populations of countries and a toggle switch that flips between 'sold' and 'unsold'. (This works with a measure that checks is a country is present in a sales table and assigns a 1 or 0 which is then used as a filter on the table visualisation).
Various slicers in the dashboard are used to filter the data model and retain the details of sales. When 'unsold' is selected therefore, the relevant countries are already filtered out of the countries data table and it is not possible to display them with their populations.
At the moment the workaround is to use a duplicate countries table that only has a one way filter, so that the rows remain regardless of filtering. This means that other slicers which interact with the rest of the data model don't filter the table visualisation as desired.
I am sure this must be possible using some combination of CALCULATE(), FILTER() and ALL() but I haven't managed to achieve this.
N.B. I can force the unsold countries to appear in a table visualisation using a constant measure (with formula: measure_name = 0) in a column .
Apologies if this is not very well explained, any help much appreciated.
Thanks for reading,
S
Image attached to (hopefully!) explain problem better.
Real scenario is more complicated hence not screenshotting from PBI.

DAX Joint value

I am trying to create a measure in DAX to find the joint value (sum) of a fact table by filtering two dimension tables to have the same column value.
Here's an image of the relationship
Each Department in Users are linked to table Registret. They are giving resources to projects. The table Projects are Taking Resourcs. What I am trying to accomplish is a measure that can find the amount a department uses of it's own resources. So I figure if I can filter Registret[Users] and Registre[Project] where Users[Department] = Projects[Department] I would get the value.
I'd like to use the Projects[Department] as a basis. So that table below would show the amount of internal department registration by each Department in Projects.
Department(Projects) InternalRegistration
A Value
B Value
So far I've been trying with something like
CALCULATE(Registret[Registret]; FILTER(Users; Users[Department] IN ALLSELECTED(Projects[Departments])))
But this will only show the correct value if I in a slicer single out a Department from table Projects. Is it possible the solution is some Joint table between Users and Projects?
Edit:
The top table shows the matrix of joint values in Registret between Users and Projects.
Edit2:
Image of my table data.
Notice that the filter arrows only point downward. This means that selecting Projects[Departments] isn't going to filter Users[Departments] since there is no filter path connecting them. You are also missing the SUM function in your measure.
Try tweaking your measure to the following:
= CALCULATE(SUM(Registret[Registret]);
FILTER(Users; Users[Department] = SELECTEDVALUE(Projects[Departments])))
If you're working in a matrix or a table, the SELECTEDVALUE should pick up the row/column filter context from the visual, whereas ALLSELECTED only picks up filter context from slicers or report/page/visual level filters.
You can also use ...IN VALUES(... instead of ...= SELECTEDVALUE(....
= CALCULATE(SUM(Registret[Registret]),
FILTER(Users, Users[Department] IN VALUES(Projects[Department])))
Both of these should produce the following:

Is it possible to use a slicer as a parameter to a DAX Summarize function?

I have a FactLosses Table, and a DimAccumulation table. I have brought them into PowerBi and I have placed a slicer to choose which accumulation zones i am interested in.
Once the user has selected the zones, i want to perform a group by year on the losses and sum the losses into year buckets. But only on the data that applies to the zones the user picked.
I am using the following DAX code to do the group by like so...
Table = SUMMARIZECOLUMNS(FactForwardLookingAccumulation[Year], "Losses By Year", SUM(FactForwardLookingAccumulation[Net Loss Our Share Usd]))
The problem is the new table always produces the same result. i.e When i make changes to which accumulation perils should be included it makes no difference to the summation. (it is summing the entire table)
I'd like to use the slicer to filter the fact table and then have the DAX query run on the filtered list. Is this possible?
If you want these tables to be responsive to filters or slicers on your report, then you can't write these as calculated tables that show up under the Data tab since those are computed before any filtering happens.
To get what you want, you have to do everything inside of a measure, since those are what respond to slicers. If you're looking for the max loss year once the grouping and summing are completed, you can write a measure along these lines:
Year Max =
VAR CalculatedTable = SUMMARIZECOLUMNS(FactForwardLookingAccumulation[Year], "Losses By Year", SUM(FactForwardLookingAccumulation[Net Loss Our Share Usd]))
RETURN MAXX(CalculatedTable, [Losses By Year])
Writing it this way will allow the calculated table to respond to your slicers and filters.

One-to-many relationship always changed into many-to-one by PowerBI

I have two tables from Azure SQL in PowerBI, using direct query:
EMP(empID PK)
contactInfo(contactID PK, empID FK, contactDetail)
which have an obvious one-to-many relationship from EMP.empID to contactInfo.empID. The foreign key constraint is successfully enforced.
However I can only create a many-to-one relationship (contactInfo.empID to EMP.empID) in PowerBI. If I ever try the opposite, PowerBI always automatically converts the relationship to many-to-one (by swapping the from and to column), which prevents me from creating visuals. Does PowerBI think the two are equivalent?
Update:
What I'm doing is to just create a table in PowerBI showing the join results of these two tables. The foreign key constraint is contactInfo.empID REFERENCES EMP.empID, which is many-to-one. That should not be a problem, I guess, since I can directly query the join using SQL.
Please also suggest if I should create the foreign key in the opposite direction.
More info on failure to create visual
The exact error message is:
Can't display the data because Power BI can't determine
the relationship between two or more fields.
Version: 2.43.4647.541 (PBIDesktop)
To reproduce the error:
DB schema is as follows:
What I want is a table in PowerBI showing contact and sales info of am employee, that is, joining all the four tables. The error will occur when VALUES of the table visual contains "empName, contactDetail, contactType, productName", however, error will NOT occur if I only include "empName, contactDetail, contactType" or "empName, productName". At first I thought the problem may lie in the relationship between contactInfo and emp, but it now seems to be more complicated. I guess it may be caused by multiple one-to-many relationships?
Expanding my comments to make an answer:
Root of the Problem
In your data model, a single employee can have multiple contacts and multiple sales. But, there's no way for Power BI to know which contactDetail corresponds to which productName, or vice versa (which it needs to know to display them together in a table).
Deeper Explanation
Let's say you have 1 emp row, that joins to 10 rows in the sales table, and 13 rows in the contactInfo table. In SQL, if you start from the emp row and outer join to the other 2 tables, you'll get back (1*10)*(1*13) rows (130 rows in total). Each row in the contactInfo table is repeated for each row in the sales table.
That repetition can be a problem if you do something like sum the sales and don't realize a single sales record is repeated 13 times but might be fine otherwise (e.g. if you just want a list of sales and all associated contacts).
Power BI vs. SQL
Power BI works slightly differently. Power BI is designed primarily to aggregate numbers, and then break them down by different attributes. E.g. sales by product. Sales by contact. Sales by day. In order to do this, Power BI needs to know 100% how to divide numbers up between the attributes on your table.
At this point, I'll note that your database diagram doesn't include any obvious metrics that you'd use Power BI to aggregate. However, Power BI doesn't know that. It behaves the same whether you have metrics to aggregate or not. (And failing all else, Power BI can always count your rows to make a metric.)
Let's say that you have a metric on your sales table called Amt Sold. If you bring in the empName, productName, and Amt Sold columns, Power BI will know exactly how to divide up Amt Sold between empName and ProductName. There's no problem.
Now add in contactDetail. Using your database diagram, Power BI has no way of knowing how an Amt Sold metric in the sales table relates to a given contactDetail. It might know that $100 belongs to empID 27. And that empID 27 corresponds to 3 records in the contactInfo table. But it has no way of knowing how to divide up the $100 between those 3 contacts.
In SQL, what you'd get is 3 contacts, each showing the $100 amount sold. But in Power BI, that would imply $300 was sold, which isn't the case. Even equally dividing the $100 up would be misleading. What if the $100 belonged entirely to 1 contact? So instead, Power BI shows the error you're seeing.
My Recommendations
If you can, I recommend changing your data model before your bring it in. Power BI works best with a single fact table, which would contain your metrics (like amount sold). You then join this fact table to as many lookup tables as you like (e.g. customer, product, etc.), directly. This allows you to slice & dice your metrics with any combination of attributes from any of the lookup tables. I would recommend checking out the star schema data model and the concept of lookup tables: powerpivotpro.com/2016/02/data-modeling-power-pivot-power-bi
At the very least, you would want to flatten your tables (i.e. merge the contactInfo and sales tables into a single table before importing them into your data model.
It may be that Power BI isn't the best tool for what you're trying to accomplish. If all you want is a table showing all sales & contact info for an employee, without any associated metrics, a regular reporting tool + SQL query might be a better way to go.
Side Note: You can't reverse a many:one relationship to get past this error. The emp table contains one row per empID. Both the contactInfo and sales tables contain multiple rows with the same empID. This means the emp table is necessarily the "one" side of the relationship to both those tables. You can't arbitrarily change that.