I am trying to find the maximum route for each day based on the count of cars in PowerBI/DAX.
An example of my data is as follows:
Date Route Count
01-Nov-17 A 10
01-Nov-17 B 5
02-Nov-17 A 2
02-Nov-17 C 22
03-Nov-17 B 2
Hence I want to find the max count of route for each date and display the results of a table like so...
Date Route Count
01-Nov-17 A 10
02-Nov-17 C 22
03-Nov-17 B 2
Any suggestions would be very much appreciated.
Thanks,
Fiona
First, define measure for max car count:
[Max Count] = MAX( Cars[Count] )
If you drop this measure into a pivot against dates, it will show you max car counts per date.
Define second measure:
[Max Routes] =
VAR Period_Max_Count = [Max Count]
RETURN
CONCATENATEX (
FILTER ( Cars, [Max Count] = Period_Max_Count ),
Cars[Route], ","
)
This measure will return a string of routes per date that have max count. You need a list instead of one value because of potential ties - multiple routes might have the same max count per period. It's not in your data example, but just to demonstrate this, I added an extra record for the first date:
The way this measure works:
first, it saves max car count per date into a variable.
second, it filters car table to select only routes that have count equal to max count for the date.
third, it iterates over the filtered table and concatenates route names into a list separated by comma.
Right-click the table choose New quick measure
In Calculation drop-down select Max per category
In Base value field, drag the Count column. In this, the value will be aggregated to Sum by default so instead change it to Max of Count
In Category field, drag the route column
Voila! Magic happens! The measure that is created, when plotted against the axis Route will give Max(Count) per Route.
Here is what the DAX will look like:
Count max per route =
MAXX(
KEEPFILTERS(VALUES('Table1'[route])),
CALCULATE(MAX('Table1'[Count]))
)
(so one can directly use this DAX without wanting to drag but i dont understand the DAX at this moment tbh)
Lucky reference for me:
https://learn.microsoft.com/en-us/power-bi/desktop-quick-measures
Create a calculated column with formula:
MAX = IF(CALCULATE(
MAX(Table1[Count]);
FILTER(
Table1;
Table1[Date] = EARLIER(Table1[Date])
)
) = Table1[Count]; Table1[Route]; BLANK())
Create your table and make a page level filter to show all non-blank values of Table1[MAX].
Related
I have some Fact Revenue, I am trying to group by Conca, and display the values only if negative…
For doing it I have this calculated column:
=
VAR name1 = Revenue[Conca]
VAR name2=
CALCULATE (
SUM ( Revenue[CostOfQuality] ),
FILTER ( Revenue, Revenue[Conca] = name1 )
)
RETURN
if (name2>0, 0, Revenue[CostOfQuality])
It works:
(highest value is 0 as expected):
Now...
If I drag fiscal year it stops working:
Why is it that I see numbers higher than 0?? (I want it to still work even if I bring other filters...)
a calculated column is computed computed once on the whole dataset after the data are loaded, and is basically a "static column".
Whatever the expected result, you are looking for a measure, which gets computed in the current context
Calculated columns and calculated tables are different from measures, since they are static: You can filter them, but they don't recalculate on filter changes.
I think that the following formula summarize pretty well what I want to achieve:
date diff =
ABS (
DATEDIFF (
data_table[login_date],
SELECTEDVALUE ( 'Date'[Date] ),
DAY
)
)
but it returns me the following error
A single value for column 'login_date' in table 'data_table' cannot be determined. This can happen when a measure formula refers to a column that contains many values without specifying an aggregation such as min, max, count, or sum to get a single result.
In other word I want have a column in my data_table with date diff calculated dynamically based on min slicer date selection.
My final goal is to filter out dynamically users that has not been logged for the last 3 months based on the slicer date range.
Here is the dataset
user_id, login_date
111, 01/02/2021
222, 02/15/2021
444, 03/15/2021
555, 01/15/2021
I want user ID to be filtered out when the number of days between the max date of the date range and the day of the last connection is higher than 90 days.
Edit
I'm adding a different formula I'm working on but having few issues to make it work
active users = CALCULATE( DISTINCTCOUNT(data_table[id]), ( FILTER ( VALUES ( data_table[id] ), DATEDIFF(IF( ISBLANK(SELECTEDVALUE(data_table[login_date])),[Min range date],SELECTEDVALUE(data_table[login_date])),[Max range date],DAY) < 90 ) ))
You can't have a dynamically calculated column, but you can use a measure to do this. The issue that you have with your calculation is that it needed to do a row by row evaluation, rather than over a column. That is why you get an 'A single value for column 'login_date' in table 'data_table' cannot be determined' error.
In this case you can use SUMX, as this is a iterator and it will do row by row. So using the following measures:
Selected Date = SELECTEDVALUE('Calendar'[Date])
This reads the date selected. You can wrap it with a MIN/MAX if needed depending on how your slicer is set up. You can change the slicer to single select, it you just want one value.
Date Calc = SUMX('Table', DATEDIFF('Table'[Login_date], [Selected Date], DAY))
This uses SUMX to calculate on a row by row level.
You can then use this measure to drive your visual. In this example I've filtered out those over 30 days since the login
If you choose a new date, it will recalculate straight away. This should set you on the right path for your use case.
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
Power BI newbie here and I'm trying to figure how to craft my DAX to manipulate my measure values based on certain criteria in the other two tables.
Currently I have 2 separate tables which are joined by a One to Many relationship and a separate Measures table. (Total Sales Price is computed as sum of Sales Price)
My aim is to create a new measure where Total Sales Price is multiplied by 1.5x when DIM_Product_Type[Product Category] = "High".
New Measure =
CALCULATE (
SUM ( FACT_PriceDetails[Sales Price] ),
FILTER ( DIM_Product_Type, DIM_Product_Type[Product Category] = "High" )
) * 1.5
However this returns no values in my visual and I'm trying to discern if its a matter of the table joins or the DAX expressions.
Thank you for your time!
Your measure seems good.
It will select only those products with a Product Category of "High" and multiply them by 1.5 to give you result. i.e. Give me the sum of all "High" Product category Price details multiplied by 1.5.
What you need to check is:
Product Serial Numbers match across the two tables
Your Product Category does indeed contain the category "High"
You have entries in FACT_PriceDetails that link to a DIM_Product_Type that has a category of "High"
Check you have not set any filters that could be hijacking your results (e.g. excluding the "High" product category product type or the realated fact/s)
Option-1
You can do some Transformation in Power Query Editor to create a new column new sales price with applying conditions as stated below-
First, Merge you Dim and Fact table and bring the Product Category value to your Fact table as below-
You have Product Category value in each row after expanding the Table after merge. Now create a custom column as shown below-
Finally, you can go to your report and create your Total Sales measure using the new column new sales price
Option-2
You can also archive the same using DAX as stated below-
First, create a Custom Column as below-
sales amount new =
if(
RELATED(dim_product_type[product category]) = "High",
fact_pricedetails[sales price] * 1.5,
fact_pricedetails[sales price]
)
Now create your Total Sales Amount measure as below-
total_sales_amount = SUM(fact_pricedetails[sales amount new])
For both above case, you will get the same output.
I have the simple dataset as below:
I need to permit summing the DistanceTraveled column in a "Measure" given date filters selected, and date order, to allow a cumulative total. The data model is dead simple as it only have one date dimension:
My DAX for the measure is:
Measure = CALCULATE(SUM(ActivityReport[DistanceTraveled]), FILTER(Timestamp,Timestamp[Timestamp] <= MAX(Timestamp[Timestamp])))
I know I must be missing something simple, how can I create a cumulative total given the filtered and increasing Timestamps for column DistanceTraveled?
I think you forgot to include all dates, Try this..
Measure = CALCULATE(
SUM(ActivityReport[DistanceTraveled]),
FILTER(ALL('Timestamp'[Timestamp]),
Timestamp[Timestamp] <= MAX(Timestamp[Timestamp])
)
)
What I ended up doing:
Measure = CALCULATE(
SUM(ActivityReport[DistanceTraveled]),
FILTER(ALLSELECTED(ActivityReport),
ActivityReport[Timestamp] <= MAX(ActivityReport[Timestamp])
)
)