DAX CALCULATE() doesn't seem to be overriding pivot filter - powerbi

I am learning to use Power Pivot and write DAX and I am working through a book I bought written by Rob Collie and Avichal Singh called "Power Pivot and Power BI".
Early on it explains what happens when using CALCULATE() in a measure. A key point of understanding is explained as follows:
If a filter argument acts on a column that IS already on the pivot, it
will override the pivot context for that column
So in a simple table called "GSR" I have a series of invoices with an invoice date, a product and an amount. I have another column that converts all invoice dates to the last day of the month to gather them together. I have created a measure called "Total orders" that is counting the number of rows.
I have created a pivot of this data with:
Products in the rows
Month end in the columns (but I've actually chosen Month and Year from the automatic breakdown Power Pivot has done on my Month_End column)
Orders in the values
This pivot renders correctly.
Now the issue:
I've created two slicers that are feeding off two disconnected tables; one containing month numbers, and one containing years. Based on the selection from each of these I have a measure that creates a month end using the EOMONTH(DATE(),0). This measure is called "Comparison_Month_End".
I then have another measure called "Compare_Orders" that contains the following:
CALCULATE([Total orders],FILTER(GSR,GSR[Month_End]=[Comparison_Month_End]))
The point of all of this - this is meant to get the orders from the GSR where the month and year match the slicer selection. I want this value to appear in the pivot for every month selected i.e. not filtered by the pivot.
It doesn't work, however. This seems to me to be counter to what the book says, which is that if the filter in the measure is applied to a column on the pivot (in this case Month_End), the pivot filter is overriden. So, for example, if I have 31-Mar-18 in a column on my pivot and the comparison month end is 31-Jan-18, I would expect to see the January orders within "Compare_Orders" sitting next to the March orders, the February orders, the December orders and so on, but it only appears next to January.
To me this is doing exactly the same as an example in the book where there is a pivot with Year in the rows, Total Sales in column 1 and then 2002 sales in column 2. Column 1 shows sales for each year, column 2 shows the same sales figure (i.e. 2002 sales) against every row, even where the row year is 2001, 2003 or 2004. The 2002 Sales measure is using CALCULATE() summing Total Sales, filtering on "Sales[Year] = 2002".
Could anyone please explain why what I expected to happen doesn't seem to be happening please?
Thank you.

CALCULATE does indeed override the filter context when evaluating its first argument; using the rows provided to its second argument as the new filter context. However; CALCULATE does not alter the filter context when evaluating its second argument, and so pre-existing filters remain unless they are explicitly removed.
In FILTER(GSR,GSR[Month_End]=[Comparison_Month_End]), FILTER only iterates over rows of GSR that are present in the pre-existing filter context (the pivot context). To get all rows, use ALL:
CALCULATE([Total orders],FILTER(ALL(GSR),GSR[Month_End]=[Comparison_Month_End]))

Related

DAX & Power Query - Removing transaction line if sale is returned

First time posting, thanks in advance !
I have a simple sales table acting as a data source.
In this table I have all my dimensions and facts, the data model is not organized as a star schema.
I believe this question does not require the data model to be optimally built.
One column tracks the Sales Quantity and shows -1 if the item is returned.
In Power Query.
I wish, for all returns, to eliminate the line with the -1, but also the associated line with the +1 sale.
I do not wish to simply filter by the Invoice Number and remove it, as in the same invoice I may have other items who were not returned.
I wish to have in my final table only final records.
Thank you
Did not manage to identify a way to tackle the issue in Power Query as of yet.
Edit, addition of further context
Dataset abstract:
I would like to keep the green row and remove the yellow ones.
One invoice features three lines, two for one item being sold and returned, and one for an item being purchased for good. That latter one is to stay in the records.
[IMAGE : Excel version of relevant column in data base ]
https://i.stack.imgur.com/CiiiC.png
Because I do not know the exact nature of your data, I will give you a general solution for your problem, which will help you immensely.
First, I will transform your data into facts and questions. Then I will answer the questions depending on my experience analyzing many different datasets; last but not least, I will provide you with the solution.
Facts,
[Sales Amount Include Tax] column values for Return Sales are negative numbers because excel format negative numbers by including them with parentheses, as your data shows.
The Original Sale record and the Return Sale record must have the same values for these columns, which we will use to know the Original Sales record:
The absolute value for the [Sales Amount Include Tax] column.
[Invoice No], [Department], [Sub Dept], [Sub Dept GROUP], [Item Code] columns.
This point is critical because we will use these columns to know the Original Sales record.
Questions,
Is the Item code column value similar to the original sale row and the returned sales row?
My answer: It should be because you are returning the same item that the Item code column describes, but I am concerned that your data shows that the first two rows don't have the same Item code. Is it by mistake?
Is the Sales Quantity column always filled with -1, even if the original sales quantity was, for example, three pairs of shoes?
My answer: The Sales Quantity column should describe the number of items someone bought, so if I originally bought 2 things but didn't like them for a reason, I will return two items so that the column value will be -2.
If my above assumptions are correct, you need to do the following in the Power BI query:
1. Import your Sales table to Power BI. See this image that shows the test data I used.
2. When you import your data and see it in the Power Query Editor, you will see that the Sales Amount Include Tax column value shows minus rather than parentheses for Return Sales Rows, as you can see in this image.
3. Create a copy of your Sales table and Rename it to Returned Sales, then filter this table to include only [Sales Amount Include Tax] that are less than 0, as you can see in this image.
4. Filter the Sales table to include only [Sales Amount Include Tax] greater than or equal to 0, as you can see in this image.
P.S. Now comes the fun part :)
1. In Returned Sales table, add a custom column name it ReturnedSaleFlag, then give it a value of 1, as you can see in this image.
2. Change ReturnedSaleFlag column type to Whole number.
3. In Returned Sales table, transform [Sales Amount Include Tax] to an Absolute Value, as you can see in this image.
4. Now you need to return to the Sales table and merge it with Returned Sales table using multiple columns which are the column listed in the second point of the fact section, as the image shows. Also, see this link that describes how to Merge query based on multi columns.
5. Expanded the new Returned Sales column in Sales table and only select ReturnedSaleFlag column and make sure to remove the check from use original column name as a prefix, as the image shows.
6. Finally, all your previous hard work created a flag in your Sales table that will let you know the Sales record that had been returned. :)
7. Now you filter the Sales table to keep the records that only have null values for the new ReturnedSaleFlag column then remove this column, as the image shows.
8. In the end save and apply and analyze your Sales and your extra info in the Returned sales.
I hope I helped in a way; if so, please mark this as an answer and vote for it :)

Calculate Works until i add FILTER

I'm learning DAX and I'm trying to make a measure for Sales Last year.
this formula works :
Sales LY = CALCULATE([Sales CY],SAMEPERIODLASTYEAR(Date[Date]))
But when I add FILTER to the measure, it gives me the values from the current year like "Sales CY"
Sales LY = `CALCULATE([Sales CY], Filter (dim_date, SAMEPERIODLASTYEAR (Date[Date]) ))`
I already have a date filter on the page relative date in this year
the invoices Table and Date table are joined on the date of the creation of the invoice (createdat)
Any ideas what's the meaning behind the things in blue circles?
The FILTER function expects a condition that can be checked for each row of the table instead of a column of dates returned by SAMEPERIODLASTYEAR, so I wouldn't expect the second version to work.
I think the bits circled in blue are emphasizing that you are connected an imported data table to a DirectQuery table (different storage modes).

Return Difference of Value Given 2 Different Date Slicers

I have 2 date slicers and a measurement which is [Profit], I would like to return the difference in Profit given the date selections. Please see below for detail.
Date Slicer 1: 3/7/2021-3/13/2021
Date Slicer 2: 3/14/2021-3/20/2021
Profit given Date Slicer 1: 10
Profit given Date Slicer 2: 15
Value I am trying to get = 5 (15-10)
If the two slicers come from the same Date column, both periods do not intersect each other and you get a filter without dates.
Possibly there are better solutions but one of them would be to use a Harvester Filter (Creating an additional table containing a copy of the date column unrelated to the model, aka Disconnected Tables)
Before moving on to the next part you can verify that the filter contains the same dates but since it is a disconnected table, it does not filter the model, yet
For the [Profit given Date Slicer 1] you can use the original measure
For the [Profit given Date Slicer 2] you must change the filter to:
DATESBETWEEN(
'Dates'[Date],
MIN(HarvestingDates[Date]),
MAX(HarvestingDates[Date])
)

Date filtering of DAX measure in pivot chart

I have created 3 DAX measures in Power Pivot to calculate backlog value and I have an issue with filtering in pivot chart. When I filter out a specific time period, the backlog calculates only based on filtered dates. Instead of filtering, I would like to only "zoom in" to some specific time-range.
Measures
Opened:=CALCULATE(COUNTA([CreatedOn]))
Closed:=CALCULATE(COUNTA(Ticket[ClosedOn]),USERELATIONSHIP(Ticket[ClosedOn],'Calendar'[Date]))
Backlog:=CALCULATE([Opened]-[Closed],FILTER(ALLSELECTED('Calendar'),'Calendar'[Date]<=MAX('Calendar'[Date])))
Based on example data below, without filtering any dates the backlog value is following:
Date;Backlog
1/1/2021;1
2/1/2021;3
3/1/2021;1
4/1/2021;3
When I filter dates excluding 1st of January, I get following values:
Date;Backlog
2/1/2021;2
3/1/2021;1
4/1/2021;3
I want to get same values as without filtering the date. I just want to to "zoom in" on some specific date range. In my case i have 1 year of input data and want to see the backlog evolution of last 8 weeks. So when I filter last 8 weeks, my first week shows only value calculated for that week, but instead it should take into account all the values from previous periods + the result of first week
Example data
TicketNumber;Type;CreatedOn;ClosedOn;Status
ticket1;Service Request;1/1/2021;1/3/2021;Closed
ticket2;Incident Record;1/2/2021;1/3/2021;Closed
ticket3;Incident Record;1/2/2021;1/5/2021;Closed
ticket4;Service Request;1/4/2021;;Open
ticket5;Service Request;1/4/2021;;Waiting for
Fixed thanks to my colleague! :)
I had to change ALLSELECTED to ALL
Backlog:=CALCULATE([Opened]-[Closed],FILTER(ALL('Calendar'),'Calendar'[Date]<=MAX('Calendar'[Date])))

Subtracting measure value from each row of a table in Microsoft Power BI

I have created two slicers in Power BI for Month and Year. These take the month and year value and in return generate a date.
Eg. Month - May & Year- 2019 generates 01/05/2019 with the help of the a measure formula :
MyFilterDate = DATE(SELECTEDVALUE(ListoY[Year]),SELECTEDVALUE(ListoM[Month],0),"01")
I want to subtract this date with one that is already in a column in the table.
I'm facing an issue when I try to subtract the measure from the existing column by writing DAX.
SUBVALNEW = DATEDIFF([MyFilterDate],Table[Date],DAY)
But when I try to do so, the result is not right. In fact when I try to check the value of [MyFilterDate] in the Data Model, it is not the same value as one calculated in the measure. (It instead looks like it displays the date in Table[Date])
Is there any way to subtract a Dynamically chosen date from a date in a column?
Any help would be appreciated.
I understand what your thinking patern is but power bi works a bit different. Dynamic measures cannot be used with calculated columns. When doing so the value of the measure is not set.
The way to go about this is by creating a Date table:
Date = CALENDAR(MIN(CalendarWeek[Date]);MAX(CalendarWeek[Date]))
Do NOT connect it to the model. From here you can make 2 slicers (based on the Date table). One your set to the month and the other to the year.
Next step is to adjust the MyFilterDate
MyFilterDate = DATE(SELECTEDVALUE('Date'[Date].[Year]);SELECTEDVALUE('Date'[Date].[MonthNo]);"01")
Make SUBVALNEW a measure (cannot be a column because it is dynamic!)
SUBVALNEW = DATEDIFF([MyFilterDate];SELECTEDVALUE(CalendarWeek[Date]) ;DAY)
Ass the Measuer to your visual, see end result below)