DAX How to Adjust Dates Based on Selected Value of Slicer - dax

Here is my setup:
I have a date slicer that I created by doing this:
d_date = Calendar(min('Table_1'[CTD]),max('Table_1'[CTD])
Here is what my dax looks like for my variables currently:
var FirstVisibleVDate = Min('d_date'[Date])
var LastVisibleDate = Max('d_date'[Date])
My problem(s):
Problem 1: I am doing a running average, I want the running average to adjust itself based on the dates selected in the slicer. I don't think this is possible, is it?
So basically, something like this:
var FirstVisibleVDate = Min(value set in the date slicer)
var LastVisibleDate = Max(value set in the date slicer)

Date range=
Var MinDate = CALCULATE(MIN(Table1[transaction date]),ALLSELECTED(Table1[transaction date]))
Var MaxDate = CALCULATE(MAX(Table1[transaction date]),ALLSELECTED(Table1[transaction date]))
Source:
https://community.powerbi.com/t5/Desktop/Capture-Time-Slicer-Minimum-Value/m-p/820372

If you are going to make a selection over the slicer then that will limit the rows that are visible in the Matrix visual, you will only see the result for the dates selected, so you will have to create a duplicate disconnected Date table that will not filter the rows of the visual.
I have made a couple of forum post on this topic as well as some videos:
Posts:
https://forum.enterprisedna.co/t/dax-calculation-for-choose-n-specific-date/16408
https://forum.enterprisedna.co/t/learning-resources-about-disconnected-date-tables/15416/2
https://forum.enterprisedna.co/t/cumulative-transactions/11803/19
Videos:
https://www.youtube.com/watch?v=WFJThyfQt-A&ab_channel=AntrikshSharma
https://www.youtube.com/watch?v=fLWfdlAaHlQ&ab_channel=AntrikshSharmaAntrikshSharma

Related

DAX FILTER works with DATE() literal, but not SELECTEDVALUE()?

In PowerBI, I have a table of prices (ItemID, ItemName, Price, EffectiveStartDate, EffectiveEndDate), and I'm trying to return all the prices that are effective on a given date (selected by the user or the evaluation context. On my report canvas I have a table visual with all the items and the details (above). If I declare a variable and assign a literal value to it, the filters work fine.... like this:
VAR CurrentDate =
DATE(2022, 3, 15)
RETURN
FILTER (
Ingredients,
[EffectiveStartDate] < CurrentDate
&& [EffectiveEndDate] > CurrentDate
)
but if I try to assign CurrentDate the value from my harvester measure, it fails. (somehow the inequality filters are being ignored ). I have a slicer (dropdown) to pick a date, and SELECTEDVALUE('DimDate'[Date}) to retrieve the value. But when I try to use that in my filter, it fails:
VAR CurrentDate =
SELECTEDVALUE('DimDate'[Date])
RETURN
FILTER (
Ingredients,
[EffectiveStartDate] < CurrentDate
&& [EffectiveEndDate] > CurrentDate
)
Any idea why this is happening? And how do I fix it?
I was expecting the two filters to act the same (the literal filter with DATE() and with a variable, but not so. When I set the value of a variable using SELECTEDVALUE(), it seems to ignore the variable in my FILTER() statement.
If you want a calculation to depend on a slicer, You need a Measure, NOT a Calculated column or Calculated table. Calculated columns and calculated tables are generated on refresh and physically stored in your model, so the slicers can filter them, but the slicers can't change the value of the calculations.
Measures are not persistent but are calculated as needed based on changes to filters and slicers. E.g. you could use a measure like the following one to filter ingredients:
Filtered Ingredients =
VAR CurrentDate = SELECTEDVALUE(DimDate[Date])
RETURN
CALCULATE(
MAX(Ingredients[Name]),
Ingredients[EffectiveStartDate] < CurrentDate
&& Ingredients[EffectiveEndDate] > CurrentDate
)

Filter Recent date in filter

I want the Slicer in Power BI to select the most recent date of the selection to be selected automatically.
Here is an example of the drop down:
https://i.imgur.com/IykHSlI.png
This drop down differs from the Client selection.
I solved this issue the following way:
I created one Report with a filter to Default_Date (which opens first)
I used a Calculated Column [Default_Date] to populate the filter (which is hidden)
In my case the user wanted to see Yesterday's data as the default date so I selected 'Yesterday' on my filter.
Then I put a button that opens another duplicated copy of the Report [Hidden Tab] that contains a full calendar filter, so the user can select any other dates he likes, this hidden report has another button that returns the user to the main report [if he wants to].
picture of my filter (which I collapse and hide under a color box/banner)
Here is the formula for the calculated column (used in the filter):
Default_Date =
VAR TodaysDate =
TODAY()
VAR YesterdayDate =
TODAY() - 1
VAR reportDate =
SWITCH(TRUE(),
'Calendar'[Date] = TodaysDate, "Today",
'Calendar'[Date] = YesterdayDate, "Yesterday",
"Before Yesterday"
)
RETURN
reportDate
Use Default_Date in your filter, and you can replace TODAY() with
CALCULATE(Max(Table[Date]),All(Table))
and remove what you don't need.
If you want to get the Last Date of selected items, then
CALCULATE(Max(Table[Date]),ALLSELECTED(Table))
Table may need to be in quotes to work: 'Table'[Date]
I hope this helps.
There isn't to set a default value in Power BI, but there are a few around about ways. First you can try Persistent Filters that can preserve the filters selected. The other option, is to create in your data set, if you have a calendar table, or are able to add it to your column a current date flag, that you can apply as a filter to your report.
For example you can use the TODAY() to return todays date, and check against your date column.
Calculated column = IF(MONTH(TODAY()) = MONTH('table'[DateColumn]) && YEAR(TODAY()) = YEAR('table'[DateColumn]), "Y", "N")
You can run the report and it will always filter on the latest date, however you will have to remove the filter if you want to see other dates. You could set up bookmarks so that you can easily add/remove filter to the report. So you would have one bookmark with latest date, and the other to remove it. You can allow the slicer box to appear when you select the 'remove current month' bookmark
Hope that helps

How to filter in crossfilter by current date and yesterday's date?

I want to make a query in crossfilter to filter all data from today's date.
Example: I have this query:
var countPerDim2 = Dim2.filterExact("1.1.2018").group().reduceSum();
So crossfilter will filter data from 1.1.2018.
But I want crossfilter to automatically get the the current date.
My reason is that I want to draw two charts to compare them.
Like :
Chart 1 by Date 1.1.2018 and Chart 2 by Date 31.12.17
How can I get the filter by yesterday's date? Is there a function like datenow() for the current day and maybe datenow(-1) for yesterday's date?
Thank you and happy new year!
Today and yesterday
To answer your immediate question, JavaScript's new Date() will return the current time and date as a JavaScript Date object. Then you just need to convert the date object to a string to match your date format.
You can use d3.time.format to produce those strings. Looks like you would want something like
d3.time.format('%-d.%-m.%Y')
(or perhaps with m and d reversed - unclear from your example whether month or day comes first)
Yesterday is something like
var date = new Date();
date.setDate(date.getDate()-1);
See the JavaScript Date documentation for more details.
Comparing two days
However, I think you'll run into a more fundamental problem, which is that crossfilter doesn't have the concept of multiple filters, so it's hard to compare one date against another in side-by-side charts.
Off the top of my head, the best thing I can think of is to "freeze" a group using a fake group:
function freeze_group(group) {
var _all = group.all().slice();
return {
all: function() {
return _all;
}
};
}
You'd apply one date filter, then call
chart.group(freeze_group(group));
on the chart you want to have that date. Now it won't change when the filter changes, and you can apply the other date filter for other charts.

PowerBi DAX equivalent for SUMIFS with current row value as filter

In Excel I could, if I was in a table called 'Sales' that had four columns
Sales
Month, CustomerId, ProductId, TotalQuantity
Jan,1, CAR,
Feb,1, CAR,
I could add a formula:
=SUMIFS(Sales[Quantity],Sales[CustomerId],[#[CustomerId]])
That would go to the Sales table and sum the CustomerID column filtered by the CustomerID of the current row where the formula has been entered.
I am attempted to replicate this in a PowerBI Calculated Row but I can't get the # working for a row reference. It comes across like
TotalQuantity = CALCULATE(SUM(Sales[Quantity]),Sales[CustomerId] = Sales[CustomerId]))
Any idea how to get the equivalent # working?
I think the key function you are missing is EARLIER. That is not surprising because it has a misleading name - it really means "Current Row". You also need a FILTER function in the Filter parameter of CALCULATE, to reset the filter context to the entire table.
So your New Column function might look like this:
TotalQuantity = CALCULATE(SUM(Sales[Quantity]), FILTER(Sales, Sales[CustomerId] = EARLIER (Sales[CustomerId])))
Here's a neat example, from the most accessible source site for DAX formulas:
http://www.powerpivotpro.com/2013/07/writing-a-subtotal-calc-column-aka-the-simplest-use-of-the-earlier-function/
And FWIW here is the official doco on EARLIER:
https://msdn.microsoft.com/en-us/library/ee634551.aspx

Get the the most recent and the one before the most recent item

I have a table with many anniversaries : Date + Name.
I want to display the next anniversary and the one after with Linq.
How can i build the query ?
I use EF
Thanks
John
Just order by date and then use the .Take(n) functionality
Example with a list of some objects assuming you want to order by Date then Name:
List<Anniversaries> annivDates = GetAnnivDates();
List<Anniversaries> recentAnniv = annivDates.OrderBy(d => d.Date).ThenBy(d => d.Name).Take(2).ToList();
If the anniversaries are stored in regular DateTime structs, they may have the 'wrong' year set (i.e. wedding or birth year). I suggest writing a function which calculates the next date for an anniversary (based on the current day) like:
static DateTime CalcNext(DateTime anniversary) {
DateTime newDate = new DateTime(DateTime.Now.Year, anniversary.Month, anniversary.Day);
if (newDate < DateTime.Now.Date)
newDate = newDate.AddYear(1);
return newDate;
}
Then you proceed with sorting the dates and taking the first two values like described in the other postings:
(from e in anniversaries orderby CalcNext(e.Date) select e).Take(2)

Resources