Get first department join date for each client from a different table using DAX - powerbi

In my scenario, many clients moving between departments and the system is tracking this using a table with columns like: ClientID/ DepartmentID/ Start date.
What if I need to get a column with first department start-date for each client? I am trying to read this to a Client profile table from the above Department association table using DAX:
FIRSTDATE('ClientDepartment'[StartDate]) will give only a single date for all clients. I am looking to get something like:
For Example (see client, department movement and result needed tables:
This is for a tabular model and I am trying to add as a column (not as measure or calculated table).
I tried:
CALCULATE (
FIRSTDATE ( ClientDepartments[StartDate] ),
ClientDepartments[ClientID] = Clients[ClientID]
)
but throwing an error
The expression contains multiple columns, but only a single column can
be used in a True/False expression that is used as a table filter
expression.

If the two tables have an active relationship, such that the Clients table is a dimension table for the ClientDepartments table, then you can simply use the following expression for the calculated column:
CALCULATE ( MIN ( 'ClientDepartments'[StartDate] ) )
If you don't have a relationship in place, use a variable:
VAR currentClient = 'Clients'[ClientID]
RETURN
CALCULATE (
MIN ( 'ClientDepartments'[StartDate] ) ,
'ClientDepartments'[ClientID] = currentClient
)

Related

Power BI - how to create measure based on conditions

I have a base table 'Orders' with a column OrderNo, this column is being used in a visual.
I have another table 'Operations' with columns: OrderNo, OperationNo, TimeTaken (this is just a numeric column). This table is related to base table with OrderNo. Please note that one OrderNo can have multiple OperationNo.
I want to add a column to my visual 'TimeRemaining', which takes all OperationNo (from Operations table) for an OrderNo and sums the TimeTaken column.
How can I achieve this?
Power bi groups the data in a visual automatically.
if they are linked you can make a calculated column in Orders
TimeRemaining =
SUM ( OperationNo[TimeTaken] )
if you want a it in the Operations specifically then:
TimeRemaining =
CALCULATE (
SUM ( Operations[TimeTaken] ),
ALLEXCEPT ( Operations, Operations[OrderNo] )
)
NOTE.
the first is for a calculated column in Orders table
the second one is for the Operations table.

Using CALCULATE to inject filter context to a calculated column - does it consist related table columns?

Calculated column does not have any filter context.
To inject a filter context we can use the CALCULATE function.
Assume I have a sales, location and date table. Sales is fact. The location and date are dimensions connected to the fact table.
Suppose I create a calculated column in the sales table with CALCULATE(SUM...)), does the injected filter context consist only rows from sales table or does the context also consist all related table columns as well?
A use case for this is for example suppose location table is linked to sales table via locationid and has state, country, then we could use ALLEXCEPT to keep only Country filter so that for each row, the SUM in CALCULATE is aggregated by Country rather than all fields in the row.
"Inject" isn't quite the right word. Using CALCULATE within a calculated column performs a context transition and then modifies that filter context using whatever arguments (if any) you supply.
You can perform the aggregate you suggest like this:
CALCULATE (
SUM ( Sales[Amount] ),
ALL ( Sales ),
FILTER ( Location, Location[Country] = RELATED ( Location[Country] ) )
)
First, the context transition turns the row context into filter context. Then, the ALL removes any filter context on Sales and the FILTER adjusts the filtering to aggregate at the granularity specified.
ALLEXCEPT doesn't work because Country isn't a column of Sales.

How to produce a snapshot table using Power BI measure

My intention is to populate days of the month to simulate a data warehouse periodic snapshot table using DAX measures. My goal is to show non-additive values for the quantity.
Consider the following transactions:
The granularity of my snapshot table is day. So it should show the following:
Take note that a day may have multiple entries but I am only interested in the latest entry for the day. If I am looking at the figures using a week period it should show the latest entry for the week. It all depends on the context fixter.
However after applying the measure I end up with:
There are three transactions. Two on day 2 and the other on day 4. Instead of calculating a running total I want to show the latest Qty for the days which have no transactions without running accumulating totals. So, day 4 should show 4 instead of summing up day 3 and day 4 which gives me 10. I've been experimenting with LASTNONBLANK without much success.
This is the measure I'm using:
Snapshot =
CALCULATE(
SUM('Inventory'[Quantity]),
FILTER(
ALL ( 'Date'[Date] ),
'Date'[Date] <= MAX( 'Date'[Date] )
)
)
There are two tables involved:
Table # 1: Inventory table containing the transactions. It includes the product id, the date/time the transaction was recorded and the quantity.
Table # 2: A date table 'Date' which has been marked as a date table in Power BI. There is a relationship between the Inventory and the Date table based on a date key. So, in the measure, 'Date'[Date] refers to the Date column in the Date table.
You can use the LASTNONBLANKVALUE function, that returns the last value of the expression specified as second parameter sorted by the column specified as first parameter.
Since LASTNONBLANKVALUE implicitly wraps the second parameter into a CALCULATE, a context transition happens and therefore the row context is transformed into the corresponding filter context. So we also need to use VALUES to apply the filter context to the T[Qty] column. The returned table is a single row column and DAX can automatically convert a single column, single row table to a scalar value.
Then, since we don't have a dimension table we have to get rid of cross-filtering, therefore we must use REMOVEFILTERS over the whole table.
the filter expression T[Day] < MaxDay is needed because LASTNONBLANKVALUE must be called in a filter context containing all the rows preceding and including the current one.
So, assuming that the table name is T with fields Day and Qty like in your sample data, this code should work
Edit: changed in order to support multiple rows with same day, assuming the desired result is the sum of the last day quantities
Measure =
VAR MaxDay =
MAX ( T[Day] )
RETURN
CALCULATE (
LASTNONBLANKVALUE (
T[Day],
SUM ( T[Qty] )
),
T[Day] <= MaxDay,
REMOVEFILTERS ( T )
) + 0
Edit: after reading the comments, this might work on your model (untested)
Measure =
VAR MaxDay =
MAX ( 'Date'[Date] )
RETURN
CALCULATE (
LASTNONBLANKVALUE (
Inventory[RecordedDate],
SUM ( Inventory[Quantity] )
),
'Date'[Date] <= MaxDay
) + 0

Calculated Column to get average from values in another table in PowerBI

This might be very basic but I am new to PowerBI.
How do I get average of values for unique ID into another table.
For eg. My Table 1 has multiple ID values. I have created another table for unique ID which I am planning to used to join other table.
I want a calculated column in table 2 which will give me average value of respective ID from table 1.
How do I get the calculated column like shown below
In stead of creating a new table with the averages per ID and then joining on that, you could also do it directly with a calculated column using the following DAX expression:
Average by ID = CALCULATE(AVERAGE('Table 1'[Values]),ALLEXCEPT('Table 1','Table 1'[ID]))
Not exactly what you asked for, but maybe it's useful anyway.
How's it going?
The quickest way I can think of doing this would be to use
SUMMARIZECOLUMNS
You can accomplish this by creating another table based on your initial fact table like so:
Table 2 =
SUMMARIZECOLUMNS ( 'Table 1'[ID], "Avg", AVERAGE ( 'Table 1'[Values] ) )
Once this table has been created, you can create a relationship.
This will work in either SSAS or in PowerBI directly.
Hope this helps!! Have a good one!!

Power BI Rank within Matrix Visual

I've spent many weeks trying to get this to work including a posting at another site. No luck. Not sure what I'm missing.
The following code gets me the table of data that I need. However, I want just the "rank" value and I want it for each row within a matrix visual.
First some background, the PowerBI page has slicers on dates and "base" product. Any given product may be sold in multiple countries. All carry the same base product suffix with a country-specific prefix.
The matrix in question displays several aspects of all the product variants for the selected base product. I want to show where each variant ranks (unit sales) within its country.
VAR tblCountrySales =
SUMMARIZE (
FILTER(
tblSalesUnits,
RELATED(tblProducts[Country])="US"
),
tblProducts[ProdID],
"Total Sales", SUM ( tblSalesUnits[Units] )
)
RETURN
ADDCOLUMNS (
tblCountrySales,
"ProductRank", RANKX ( tblCountrySales, [Total Sales] )
)
Is there a way to either pull just the rank for a single product from the above code, or, better yet, a DAX pattern that will get me the rank by unit sales of each product variant within its respective country?
I've use these statements to successfully get the product ID and country for each row within the visual.
VAR ProdSales = SUM(tblSales[Units])
VAR ProdCountry = SELECTEDVALUE(tblProducts[Country])
Any help is greatly appreciated. I assume I'm missing something with row context within the visual as a simple COUNTROWS on the table expressions above always returns "1". Being new to PowerBI and DAX I'm still trying to grasp the nuances of filter and row contexts.
The products table contains data like...
ProdID.....BaseID....Name...Country
7190...........7190.....xxxx.....US
150207190......7190.....XXXX....Panama
241807190......7190.....xxxx.....Spain
The sales table contains data like...
ProdID......SalesMonth......Units.....USD
7190........July 2010.......4563....$23491.00
150207190...July 2010.......2543....$16235.00
241807190...July 2010.......1263....$8125.00
There is a dates table as well that links the SalesMonth to the usual selection of date display formats. The two tables above are linked via ProdID, though the visuals are sliced by the BaseID. I'd attach a picture, but don't have permissions to do so.
With some more tinkering I found this solution.
Country Rank =
VAR ProdSales = SUM(tblSales[Units])
VAR ProdCountry = SELECTEDVALUE(tblProducts[Country])
VAR tblCountrySales =
SUMMARIZE (
FILTER(
ALLEXCEPT(tblProducts,tblProducts[BaseID]),
tblProducts[Country]=ProdCountry
),
tblProducts[ProdID],
"Total Sales", SUM ( tblSales[Units] )
)
RETURN
IF(ProdSales>0,COUNTROWS(FILTER(tblCountrySales,[Total Sales]>ProdSales))+1,BLANK())