7 day rolling sum not working on Power BI - powerbi

I need your help. I'm working on a Power BI project and I'd like to create a Measure that calculates the 7 day rolling sum of my number of sales.
I have a table with several columns. In one of these columns, I have the number of sales per day.
My DAX measure is supposed to sum the number of sales for the day and the 6 days before. And this process is repeated for each date.
The problem is that my code doesn't work. Here's what I have:
Actual Orders - 7DR =
VAR CurrentRow = SELECTEDVALUE(Table[Date])
RETURN
CALCULATE(SUM(Table[Sales]), DATESINPERIOD(Table[Date], CurrentRow, -6, DAY))
The problem is that I also have an Excel spreadsheet with the same calculations made with a simple SUM and my results are not the same.
Do you guys have any idea why it's not working?
Thank you.

Other than perhaps an off-by-one error, that measure looks fine. With this table
let
Days = List.Dates(#date(2023,1,1),20,#duration(1, 0, 0, 0)),
#"Converted to Table" = Table.FromList(Days, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
#"Renamed Columns" = Table.RenameColumns(#"Converted to Table",{{"Column1", "Date"}}),
#"Inserted Month" = Table.AddColumn(#"Renamed Columns", "Sales", each 1, Int64.Type),
#"Changed Type" = Table.TransformColumnTypes(#"Inserted Month",{{"Date", type date}})
in
#"Changed Type"
and this measure
Actual Orders - 7DR =
VAR CurrentRow = SELECTEDVALUE('Table'[Date])
RETURN
CALCULATE(SUM('Table'[Sales]), DATESINPERIOD('Table'[Date], CurrentRow, -7, DAY))
You get this

Check this one out:
7 day rolling sum =
VAR __LAST_DATE =
LASTDATE('Table'[Date])
RETURN
CALCULATE(
SUM('Table'[Sales]),
DATESBETWEEN('Table'[Date], DATEADD(__LAST_DATE, -6, DAY), __LAST_DATE)
)

Related

Group table and create measure based on parameter from different rows

bit new to dax and I am struggling in creating a formula.
So I need to write a mathematical calculation which =+(E4+Mx6)/2*33 for the East Silo on the same date and time only.
So the first one would be 07/11/2022 4:30 am calculation (4+4)/2*33
I tried doing the calculation but i couldn't figure out how to calculate based on the same date field
You can do it in Power Query
Mark your Parameter and Value columns
Transform - Pivot them
Add custom column from the new [E4] and [Mx6] columns
M-code should look like this:
#"Pivoted Column" = Table.Pivot(
#"Changed Type", List.Distinct(#"Changed Type"[Parameter]), "Parameter", "Value", List.Sum),
#"Added Custom" = Table.AddColumn(
#"Pivoted Column", "Custom", each ([E4]+[Mx6]) / 2 * 33)
If you want to solve it in DAX, use this measure:
Math =
VAR tbl =
SUMMARIZE(
'Table',
'Table'[Datetime],
'Table'[Silo],
"E4", CALCULATE(
SUM('Table'[Value]),
'Table'[Parameter] = "E4"
),
"Mx6", CALCULATE(
SUM('Table'[Value]),
'Table'[Parameter] = "Mx6"
)
)
RETURN
SUMX(
tbl,
([E4] + [Mx6]) / 2 * 33
)

Filter only to show durtion

Time
Value
10/3/2022 18:21:40
correct
10/3/2022 18:22:50
incorrect
10/3/2022 18:28:00
correct
10/3/2022 18:34:00
incorrect
From the above table, I want only filter out and show on the table if the time difference between "correct" and "incorrect" is > 5 minutes
This assumes there is always only two alternating rows of correct and incorrect, and returns a column showing the duration in minutes between them. You can then filter that, since you were vague on how and what to filter
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Time", type datetime}, {"Value", type text}}),
#"Added Index" = Table.AddIndexColumn(#"Changed Type", "Index", 0, 1, Int64.Type),
#"Added Custom1" = Table.AddColumn(#"Added Index", "MinuteDuration", each if [Value] = "incorrect" then null else Duration.TotalMinutes(#"Added Index"{[Index]+1}[Time]-[Time]),type number),
#"Filled Down" = Table.FillDown(#"Added Custom1",{"MinuteDuration"})
in #"Filled Down"
Here's one way to solve your problem.
Make sure your date data is sorted chronologically ascending. (this can be done in Power Query.
Create an Index Column in Power Query
Close Power Query and add the following calculated column to your table
IfNextRowOverFiveMins =
var currentRow = 'Table (2)'[index] --this should be the index on your rable
var nextTime =LOOKUPVALUE('Table (2)'[time],'Table (2)'[index],currentRow+1) --this function looks up the time for the next entry
var timeDiff = DATEDIFF('Table (2)'[time],nextTime,MINUTE) --the datediff function finds the difference in days/hours/minutes between two date values
return IF(timeDiff>=5,TRUE(),FALSE())

How to calculate average weekly active visitor using DAX in PowerBI

*Take note that Visit 1 means the first visit of the day while Visit 2 means the 2nd visit for the day.
Hello everyone,
I'm trying to calculate average weekly active visitors in PowerBI using DAX.
First, I need to calculate how many unique visitors visit the shop in one week (Mon-Sun). Based on the calendar, 5/10/2022 - 5/13/2022 will be categorized under one week, and 5/16/2022 - 5/18/2022 is another week. So for the week from 5/10/2022 - 5/13/2022, there are 9 unique visitor and for the week from 5/16/2022 - 5/18/2022, there are 3 unique visitors.
Once I found out the unique visitor for respective weeks, then I can get the average weekly active visitor by:
(9+3)/2 = 6 visitors
Hence, the answer for the example in the screenshot will be 6 visitors. The output will be used in card visualization.
Struggling to find the best way to do this, any help or advise will be greatly appreciated!
Sample Data:
https://docs.google.com/spreadsheets/d/10TsJUy-Lkdpb9Eeh5itx-XE59hytC_i5I_6UeLLHS84/edit#gid=0
I don't know enough about DAX (or Power BI) to devise a DAX only solution.
However, you can calculate the Distinct Visitors per week using Power Query M Code (Home=>Transform in Power BI), and then create a Measure to show the Average visitors per week on the card.
Power Query M Code
Edit: Change from computing weeknumber to computing start of week to avoid problems if dates span more than a year, per comment below by #weizer
let
//change next line to whatever your actual source is
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
//Don't need this column for the output
#"Removed Columns" = Table.RemoveColumns(Source,{"Visit"}),
//Set data types
#"Changed Type" = Table.TransformColumnTypes(#"Removed Columns",{{"Visitor ID", Int64.Type}, {"Date", type date}}),
//add custom column referenced to "StartOfWeek" so we can group by week
#"Added Custom" = Table.AddColumn(#"Changed Type", "WeekNumber", each Date.StartOfWeek([Date],Day.Monday), type date),
//Group by week number
// Then aggregate by week range and distinct visitor count
#"Grouped Rows" = Table.Group(#"Added Custom", {"WeekNumber"}, {
{"Date Range", each Date.ToText(List.Min([Date])) & " - " & Date.ToText(List.Max([Date])), type text},
{"Distinct Visitors", each List.Count(List.Distinct([Visitor ID])), Int64.Type}
}),
//Remove unneeded Weeknumber column
#"Removed Columns1" = Table.RemoveColumns(#"Grouped Rows",{"WeekNumber"})
in
#"Removed Columns1"
The Measure for the card will be just a simple Average function:
Distinct Visitors per Week = Average(yourTableName[Distinct Visitors])
VAR days =
SUMMARIZE(
'Sheet1'
,'Sheet1'[Date]
)
VAR Calend=
ADDCOLUMNS(
days
,"week",WEEKNUM('Sheet1'[Date])
)
VAR weeks=
SUMMARIZE(
Calend
,[week]
,"qty",COUNTROWS(VALUES('Sheet1'[Visitor ID]))
)
RETURN
AVERAGEX(
weeks
,[qty]
)

SUMX over table variable breaks when adding relationships to underlying table

Environment
I have created the two queries in Power Query
"Demo"
let
Source = Table.FromList(List.Random(1000, 20200427),Splitter.SplitByNothing()),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}}),
#"Split Column by Position" = Table.SplitColumn(#"Changed Type", "Column1", Splitter.SplitTextByPositions({0, 5, 7}, false), {"Month", "Amount"}),
#"Changed Type2" = Table.TransformColumnTypes(#"Split Column by Position",{{"Month", type number}, {"Amount", type number}}),
ConvetToMonthNumber = Table.TransformColumns(#"Changed Type2",{{"Month", each Number.RoundDown( 12 * _) + 1, Int64.Type}})
in
ConvetToMonthNumber
and "MockCal"
let
Source = Table.FromList( List.Repeat({1..4},3), Splitter.SplitByNothing(),{"CalQuart"}),
#"Added Index" = Table.AddIndexColumn(Source, "Month", 1, 1)
in
#"Added Index"
and then in the model I have two bits of DAX
Running Amount =
CALCULATE(
SUM('Demo'[Amount]),
FILTER(ALL('Demo'[Month]), 'Demo'[Month] <= MAX('Demo'[Month]))
)
and
WEIRD Run total =
VAR CalcTable = SUMMARIZE(Demo,Demo[Month],"MonthlyRollingAmounts",[Running Amount])
VAR TotalAmount = SUMX(CalcTable,[MonthlyRollingAmounts])
RETURN IF(ISFILTERED(Demo[Month]), [Running Amount], TotalAmount)
With this I can produce the following visual:
This achieves the desired result: Create a measure that sums up its slices by month.
However, when I create a relationship off this table, the SUMX stops working as expected.
The question is: Why does adding this relationship change the behavior of the SUMX? It doesn't seem to me like it should matter at all. Help is appreciated, this one is really bending my brain.
The reason for this is that in your Running Amount measure you remove any filtering on 'Demo'[Month] but this does not propagate upstream to MockCal (which I'm assuming you're using as the first column in your visual).
In general, you want to do your date filtering on your calendar table instead of your fact table. Try this instead:
Running Amount =
CALCULATE(
SUM('Demo'[Amount]),
FILTER(ALL(MockCal), 'MockCal'[Month] <= MAX('MockCal'[Month]))
)
Your WEIRD Run total should be updated as well to use the calendar table.

Power BI If Blank Then Put Value

This snippet displays the chart we are looking at and it has blanks. Instead of blanks for those dates and ID's we want to show what those values are; however, the values(Rates) may not be the same for every ID or Date. (This may happen on rare occasions.)
This snippet displays the data being pulled into Power BI from excel (Just sample data). Notice that all the dates are in order, but notice that some of the ID's do not have entries for certain dates.
I want to be able to say IF(ID is blank per this date, then put Value(Rate) that is attached to this ID).
This may not be possible to do in Power BI. We have an excel spreadsheet with similar data doing what we want but we wanted to automate by using Power BI.
Any Thoughts?
Update
I have got the measures to work in my favor, however; I need to get the total of the measure: Value Or Rate measure. I do have Value Or Rate - visual totals if I can do the same thing as the Value Or Rate measure with a total that would be great.
Please see the updated screen screenshots below.
Visual with fields
Relationships
As a measure, you could do something like below. I'm assuming that you have a model as follows:
Fact: (Date, ID, Value)
DimDate: (Date, ...)
Rates: (ID, Rate)
Dim: (ID, ...)
With these tables you'd have relationships as below:
Dim -1:N-> Fact
Dim <-1:1-> Rates
DimDate -1:N-> Fact
With the model above, you could then build a visual of:
Rows: DimDate[Date]
Columns: Dim[ID]
Values: [Value Or Rate Measure]
Value = SUM ( 'Fact'[Value] )
Rate = SUM ( 'Rates'[Rate] )
Value Or Rate Measure =
VAR Value = [Value]
RETURN
IF ( ISBLANK ( Value ), [Rate], Value )
This might not do what you want for totals - you didn't specify. So if you need visual totals you might try the following:
Value or Rate - visual totals =
SUMX (
CROSSJOIN ( VALUES ( 'Dim'[ID] ), VALUES ( 'DimDate'[Date] ) ),
[Value Or Rate Measure]
)
You could also handle this in Power Query M, assuming you have the same tables I've described above. I'm assuming each table has an associated query of the same name.
let
Source = Table.AddColumn(Dim, "Date", each DimDate[Date]),
#"Expanded Date" = Table.ExpandListColumn(Source, "Date"),
#"Merged Queries" = Table.NestedJoin(#"Expanded Date", {"id", "Date"}, Fact, {"ID", "Date"}, "Fact", JoinKind.LeftOuter),
#"Expanded Fact" = Table.ExpandTableColumn(#"Merged Queries", "Fact", {"Value"}, {"Value"}),
#"Merged Queries1" = Table.NestedJoin(#"Expanded Fact", {"id"}, Rates, {"ID"}, "Rates", JoinKind.LeftOuter),
#"Expanded Rates" = Table.ExpandTableColumn(#"Merged Queries1", "Rates", {"Rate"}, {"Rate"}),
#"Added Custom" = Table.AddColumn(#"Expanded Rates", "Value Or Rate", each if [Value] = null then [Rate] else [Value]),
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Value", "Rate"})
in
#"Removed Columns"
Here, we're doing something similar, but at a table level, instead of as a measure. We crossjoin Dim[ID] and DimDate[Date] to get a dense table of all date and ID combinations. Then we left join the original Fact table and the Rates table. Then we add a column that takes [Value] if it exists, or [Rate] if [Value] is null.