Wrong Totals Using IF and Values() in Power BI - powerbi

I am working on getting the amount of new sales and lost sales with regards to sales previous year and sales year to date. I am trying to show this in a table and then filtering that table with a year slicer.
Below are the formulas that i have used:
SalesPY = CALCULATE(SUM(SalesData[Value]),SAMEPERIODLASTYEAR('Calendar'[DateKey]))
SalesYTD = TOTALYTD(SUM(SalesData[Value]), 'Calendar'[DateKey])
NewSalesUppdate = SUMX(VALUES(SalesData[CustomerName]),IF([SalesYTD] > 0 && [SalesPY] = 0, [SalesYTD]))
LostSalesUppdate = SUMX(VALUES(SalesData[CustomerName]),IF([SalesYTD] = 0 && [SalesPY] > 0, -[SalesPY]))
LostSalesOld = IF([SalesPY] > 0 && [SalesYTD] = 0, -[SalesPY])
The NewSalesUppdate formula works as it should and sums up correctly. However LostSalesUppdate does not work, despite having pretty much the opposite formula compared with NewSalesUppdate. It seems like the IF statement never becomes true. That is strange because the LostSalesOld formula shows the right value, but it does not show the total.
All tips are appreciated!
Sample Data:
Current Result:
Notice how customer A had no YTD sales. The LostSalesOld shows -85000 in sales, but nothing is reflected in the total. The LostSalesUppdate shows nothing at all.
Desired Result:
Now one of the lost sales columns (doesn't matter which) has a value for customer A, and a total

Focusing on LostSalesUppdate, the issue is one of context. Your measure is saying "For each customer name in the SalesData table, show me last year's sales negated if they had sales last year and none this year".
The problem (and I'll admit it is subtle), is that because there are no sales for Customer A this year, Customer A is not in the SalesData table as far as this measure is concerned. Therefore, the rest of the formula is ignored.
What I would recommend is adding a separate table with a list of customers, similar to your date table (one row per customer). Then, update your LostSalesUppdate formula so that instead of pulling CustomerName from SalesData, it pulls it from your new customer table.
LostSalesUppdate =
SUMX (
VALUES ( Customer[CustomerName] ),
IF ( [SalesYTD] = 0 && [SalesPY] > 0, - [SalesPY] )
)

Related

DAX measure to extract summed quantity values for selected weeks only

I have production figures which sum the quantity of parts produced by each workstation on a weekly basis. These are shown in a matrix with workstation number on the rows and week numbers across the columns.
I want to be able to select 2 weeks and then
Display all the weeks in the range selected by a slicer.
Show the quantity values for only the first and last selected weeks.
The first part is working using a simple Week Slicer.
The second part, however, always shows the totals for all the selected weeks rather than the 2 individual week quantities.
In this example I have selected weeks 4 and 9 and therefore the expected values for quantities are 11,505 and 49,425 as shown in the Good Qty data with red frames.
The measures to extract the fist and last selected week numbers are working:
SelWeek1 = FIRSTNONBLANK(VALUES(vLink[Week]),0)
SelWeek2 = LASTNONBLANK(VALUES(vLink[Week]),0)
My measures for the week quantities are:
IF([SelWeek1]>0,
CALCULATE([Sum vGood Qty],FILTER(vLink, vLink[Week] = [SelWeek1])),
0
)
and
SelWeek2 Qty =
IF([SelWeek2]>0,
CALCULATE([Sum vGood Qty],FILTER(vLink, vLink[Week] = [SelWeek2])),
0
)
What am I missing?
Try to use below measures:
SelWeek1 = MIN(vLink[week])
Measure =
VAR _selWeek = [SelWeek1]
VAR result =
CALCULATE(
[Sum vGood Qty],
vLink[Week] = _selWeek
)
RETURN
result
and for selected week 2 change min to max in the first measure and _selWeek variable in the second measure respectively.

SUMX in DAX (PowerBi) isn´t working as supposed to

I am currently working on a PVM Analysis and everything was running smoothly. Until one of my measures fails to work.
Both measures are practically the same:
One that works:
Novo =
VAR Novo = FILTER( CODITEM,
[Revenue LY]+0=0)
return
SUMX(Novo, [Revenue TY])
The failed one:
Discontinued =
VAR Discontinued = FILTER(CODITEM,
[Revenue TY]+0=0)
return
SUMX(Discontinued,-[Revenue LY])
Both have to iterate into the "CODITEM" level. One only brings value when revenue LY = 0 and the other when revenue TY = 0.
Other measures here.
Revenue TY = sum(TotalFat)
Revenue LY = CALCULATE([Revenue TY],PREVIOUSMONTH('Date'[Date]))
In my BI filter the page by this month (so that I can see this month revenue in Revenue TY and last month revenue in Revenue LY).
I also attached the data and PBIX file in the link below:
https://drive.google.com/drive/folders/17ZJ3YwwiIaNJitIFNeaOLWNTap792ubc?usp=sharing
I can´t figure it out what this could it be.
I don't see anything wrong with your formula. When I look at your data, I see that you are filtering the base1[quantfat] column for any Codeitem quantities that are equal to 0, and then pulling any associated revenue from those items.
However, when I look at your base1 table, I can see there are no entries where unit sales are equal to=0, therefore there is no associated revenue for items with zero [quantfat] which is why I think the measure is showing up blank.

PowerBi DAX measure to sum duration of timespans filtered by current slicer

I need a DAX measure that gives me the sum of durations for multiple categories restricted by a date slicer.
In this simplified example there are 2 categories with 3 subcategories each. A DateTime Slicer on the dashboard is set to the timespan of 2nd of January 2021 noon to 6th of January midnight. I need the summed up duration of all categories in this timespan.
Input data:
A table containing multiple rows for each category with a start date and an end date.
The complicated part is that there are pauses between the timestamps.
Desired output:
A table on the dashboard containing the category and a calculated measure for the summed up duration during the sliced timespan.
When changing the slicer the meaure shall change as well.
My current solution for this problem is an M formulato create a list of all days in each timespan and to unpivot all lists. In the dashboard the count of rows gives you the number of days in the selected timespan. This solution though reqires a much larger input table and soes not work if you want to be exact on the second, only on days.
I tried so solve this via a measure but didn't make any progress worth showing here.
all datetime values are in the format dd.mm.yyyy hh:mm:ss (24h system)
I found a way to do it by using 2 measures.
First measure calculates the time during the timespan for each element:
I use one Date Table only consisting of all dates available which is the input for the slicer and the data Table called "Data".
duration_in_timespan_single =
VAR MinTs = MIN ('Date'[Date])
VAR MaxTs = MAX ('Date'[Date])
VAR MinUtcMin = MIN ('Data'[Date_Start])
VAR MaxUtcMax = MAX ('Data'[Date_End])
RETURN
IF(
AND(MinUtcMin >= MinTs, MinUtcMin <= MaxTs),
IF(
MaxUtcMax <= MaxTs,
CONVERT((MaxUtcMax-MinUtcMin),DOUBLE),
CONVERT((MaxTs-MinUtcMin),DOUBLE)),
IF(
MinUtcMin < MinTs,
IF(
MaxUtcMax > MinTs,
IF(
MaxUtcMax <= MaxTs,
CONVERT((MaxUtcMax-MinTs),DOUBLE),
CONVERT((MaxTs-MinTs),DOUBLE)
),
0
),
0
)
)
The second measure just sums up the first for each category:
duration_in_timespan = SUMX('Data',[duration_in_timespan_single])

Finding Previous year Sales in Power BI with week number

I am trying to find the Previous year sales for the same week in Power BI.I dont have any date column.
I have two table one is FACT Indicators table as shown below:
and one sales table( Fact Sales table):
I want to create one calculated field namely(Sales Previous Year) to show the previous year sales for the same week .
In 'Fact Indicators' table 'PY 52 week flag' filed shows if this week id is Previous year or not.
Week column shows the week number from 1 to 52 weeks .
Week Id shows the unique number per Market key.
'Market_Week Id Key' is the common joining key between FACT Indicators table and Fact Sales table
Please help me to find the formula for calculated field.I dont have the date field in my raw data
Every time you deal with anything related to dates, you will need to add what we call a date dimension. It will save you tons of headaches. Once you have it in you will be able to hook it into the creation of the calculated filed.
you can google power bi or ssas date dimension and find tons of information on it.
Yeah! I guess SQL Technical team can be a tough crowd.... Well! In this case, I would recommend bringing the Year into FactSales Table from Fact Indicator . You have two options here with physical relationship set up between Market Week Id Key in both tables you can build a calc column with
Year = CALCULATE(VALUES(FactIndicators[Year]))
or without relationship use LOOKUPVALUE on WeekId
Year = LOOKUPVALUE(FactIndicators[Year], FactIndicators[WeekId], FactSales[WeekId])
Sales Last Year calc colum :
SalesLastYear =
CALCULATE (
SUM(FactSales[SalesThisYear] ),
TOPN(1,
FILTER(
FactSales,
FactSales[Year] < EARLIER(FactSales[Year])
&& FactSales[Key] < EARLIER(FactSales[Key])
)
)
)

Dax Finding date based on Criteria calculated Column

I couldn't find an answer for my issue elsewhere, so trying my luck here.
I have sales table and my final result should determine if there were sales made for same person in specific period of time, for example within 7 business days. for example:
For ID 123 I have to flag it that sale for products A,B,C where within specified period.
For ID 1234 only sales of products A and B meet the criteria product C was sold in irrelevant time frame.
I've created a date table with indicators that determine for each date if the date is a working day, but i am struggling to calculate the relevant last working day
For example: I need that for 01/01/2019 i will get 10/01/2019 date, based on NUMOFDAYS and FinalWorkday = TRUE, which basically means that i have to count NUMOFDAYS times TRUE statement for each date and return corresponding date.
After that step done I think that it would be pretty easy for me to determine if the sale for a person was made in specific time frame.
If someone can give me direction for that much appreciated
Thank you in advance
You could use a DateTable like this one:
I used the following DAX-expressions for the calculated columns:
nrDays = 7
isWorkDay = WEEKDAY('DateTable'[Date],2) < 6
rankWorkingDays = RANKX ( FILTER ( DateTable, DateTable[isWorkDay] = TRUE () ),
DateTable[Date] , , ASC )
LastWorkDay = LOOKUPVALUE ( DateTable[Date],
DateTable[isWorkDay], TRUE (),
DateTable[rankWorkingDays], DateTable[rankWorkingDays] + DateTable[nrDays])
This issue can be solved by the following, since three are non-working days/holidays we can filter them out via POWERQUERY, than add an Index Column and Another column Which is basically Index column + Number of days wanted, then simply merge duplicate of dates query on Index+number of days wanted column on Index column. And we get the correct date