Measure for sum of open positions in accounting (two date columns in source) - excel

I would like to calculate the sum of open positions in a receivables account. The entries in the accounting system provide three relevant columns in the source table to that end:
booking date
due (=pay) date
amount due
I would like to have a measure that I can use for a graph, showing the total of all open positions on each day.
An open position is an amount booked with a booking date before "today" and with a due date after "today".
I tried the following approach in my Power Pivot model (with three calendar tables):
booking date related to "calendar table 1"
due date related to "calendar table 2"
Date columns of "calendar table 1" and "calendar table 2" related to a third "calendar table main"
For that formula I am getting an error message:
Hm, not sufficiently proficient in PowerPivot to solve this problem.

SumAmt:=
SUM( Source_Table[Amount] )
OpenPositions:=
CALCULATE(
[SumAmt]
;FILTER(
VALUES( Source_Table[Booking_Date] )
;Source_Table[Booking_Date] < MAX( Calendar_Main[Calendar_Date] )
)
;FILTER(
VALUES( Source_Table[Due_Date] )
;Source_Table[Due_Date] > MAX( Calendar_Main[Calendar_Date] )
)
)
Your error is pretty self-explanatory. If you use a direct column reference in CALCULATE() you can only reference a single column. You are referencing two, Calendar_Main[Calendar_Date] and either Source_Data[Booking_Date] or Source_Data[Due_Date]. This is simply not allowed, so it throws the error.
The workaround is simply to wrap complex filtering logic in table expressions and use those as arguments to CALCULATE(). Pretty much, unless you are hard-coding a literal predicate for a single column, you should be using some sort of table expression, like FILTER(), as your arguments to CALCULATE().
What we do is call FILTER() twice to check the dates. We use MAX()s because we cannot perform comparisons between column references, we need to perform inequality comparisons between scalars.
Since we're FILTER()ing over Source_Data[Booking_Date] and Source_Data[Due_Date], the references to these are evaluated in row context and refer to the value of the current row in FILTER()'s iteration. The reference to Calendar_Main[Calendar_Date] is just a column reference, so we wrap it in MAX() to get a scalar value for our inequality. The MAX() refers to the current filter context coming in from the pivot table, which would be the current row label or column label.
If you aggregate to the month level, this will give you essentially the closing balance, since we're using MAX()s. At the month level the value will be identical to that on the last date of the month.
Finally, with the inequalities you've set up, you're ignoring anything opened on the current day or due on the current day. I'd expect you want [Booking_Date] <= [Calendar_Date] and [Due_Date] > [Calendar_Date].

Related

How can I split weekly data to monthly using Excel/ Power Pivot?

My Data is in weekly buckets. I want to split the number into a monthly number but, since there is an overlap in days falling in both the months, I want a weighted average of the data in terms of days that fall in each of the months. For example:
Now, in the above picture, I want to split that 200 (5/7*200 in Jan, 2/7 in Feb). How can I do that using Excel/ Power Pivot/ Dax Functions? Any help here is much appreciated.
Thank you!
Assuming your fact table looks something like below. Values are associated with the starting date of the week it occurred.
Although it may actually be a more granular data, having multiple rows for each week with additional attributes (such as identifiers of a person, a store, depending on the business), what being shown below will work the same.
What we need to do first is to create a date table. We can do that in "Design" tab, by clicking "Date Table", then "New".
In this date table, we need to add a column for starting date of the week which the date of each row is in. Set the cursor to "Add Column" area, and input following formula. Then rename this column to "Week Start Date".
= [Date] - [Day Of Week Number] + 1
Now, we can define the measure to calculate the number allocated to each month with following formula. What this measure is doing is:
Iterating over each row of the fact table
Count the number of days for the week visible in the filter context
Add the value portion for the visible days
Value Allocation := SUMX (
MyData,
VAR WeekStartDate = MyData[Week]
VAR NumDaysInSelection = COUNTROWS (
FILTER (
'Calendar',
'Calendar'[Week Start Date] = WeekStartDate
)
)
VAR AllocationRate = DIVIDE ( NumDaysInSelection, 7 )
RETURN AllocationRate * MyData[Value]
)
Result in the pivot table will be looking like this.

I need a pivot table of the pivot table I've created

I have a fact table that covers several weeks of tasks in MS Project, and each week is timestamped with that week's week-ending date. I am trying to get the previous week's remaining work for certain tasks (they have a flag called Should Finish This Week set to TRUE).
I have a formula that enables me to create a pivot table that, when I manually sum the values column (it's basically a MIN of the previous week's remaining hours by assignment id), it gives me the result I want.
However, I cannot figure out how to "build this pivot table in DAX" so that I can summarize the resulting sum of hours by department. Right now, I just have the number of hours by task (assignment id) for last week.
Here's the formula:
Simple Min :=
CALCULATE (
MIN ( DataMerge[PreviousWeekRemainingWork] ),
AssignmentHistory[ShouldFinishThisWeek] = TRUE (),
DataMerge[BestPercentComplete2] < 1,
DataMerge[CompletedFLAG] = FALSE (),
USERELATIONSHIP ( 'Calendar'[Date], DataMerge[End of Week] )
)
And with that formula, I can output the following pivot table (this is just a small sample):
The desire is to get a SUM of the Simple Min value by Department. I've tried all the tricks of PowerPivot that I know. Here' the latest iteration of a formula I tried, but the amounts by department are all incorrect, and the grand total is off by about 1200 to the high side.
HRS Remaining More Simple :=
SUMX (
SUMMARIZE (
DataMerge,
DataMerge[ResourceDepartments_R],
DataMerge[AssignmentId]
),
[Simple Min]
)
Any help on this last formula would be greatly appreciated. When I manually sum the pivot table, I come up with ~4300 hours, which is the correct number, so I can verify the formula once given.
Thanks!

DAX average including zeroes

My question is that I'd like to calculate a daily average taking into account days with zeroes.
Let me clarify it:
I'd like to calculate the average daily value of units for each category, with the following table:
When I sum up the values for each day and category, I get:
I'd like to include in the average calculation the zeroes.
I use the following code:
SUMMARIZE(
Data,
Data[Category],
"Average",
AVERAGEX(
SUMMARIZE(
Data,
Data[Date],
"Sum of Units",
SUM(Data[Units])
),
[Sum of Units]
)
)
But the problem is that for category B it doesn't take into account those days with 0s.
Could you please guide me how to solve it?
Thanks in advance!
Jorge
One way to solve it would be to create a calendar table, which can then be used to count the number of days in any of your grouping periods. This also means you can use non standard calendars, for example something like a 4-4-5
With a calendar table created you can leverage the FIRSTDATE and LASTDATE functions in DAX.
I recommend adding a past dates column to the calendar table, which can be created using DAX with the following formula. The today function in DAX when used in a calculated column will only evaluate when the model is updated.
In my example I created a calculated column in the date table called Past_Dates
Past_dates =IF( TODAY() > [Date], TRUE(), BLANK())
So for example if I create the following measures, the Today one just being used for illustration.
Start_date:=FIRSTDATE( Dates[Date] )
End_Date:=LASTDATE( Dates[Date])
Today:=TODAY()
EndPhased:=CALCULATE( LASTDATE( Dates[Date] ), Dates[Past_dates] = TRUE())
Which when added to an empty pivot table evaluate to the following.
Note that you would want to have year somewhere in the pivot if you have multiple years of data.
The idea of having the Past flag is to keep from counting days where they would not be any data due to being in the future. So for example in September it would only use 11 days of sales and not the full 30.
As the below example shows, the finding of the start and end date even work on a Quarter basis.
So now that we have a way to get the Start and End date of a period, the next step is adding it into our Calculated measure.
In the below example, we are iterating though every unique Category name. Within the category, we are summing the units sold, and then dividing by the number of days between EndPhased and Start_Date + 1. Then averaging the results by the number of categories that have data in that period.
Average:=AVERAGEX (
VALUES ( Data[Category] ),
CALCULATE ( DIVIDE ( SUM ( Data[Units] ), [EndPhased] - [Start_date] + 1 ) )
)
It seems to me that you need to have an underlying row with the zero value in it (in your initial Data table). Right now, you don't actually have a zero value for B on 02/01/2017. If you add a row with the values | 02/01/2017 | B | 0 | I believe you will see that the average accounts for it. As things stand for you right now, I believe the pivot table actually reflects no value (blank) rather than zero value, so the zero isn't currently counted for the average.
I think the best way is to add the missing zeroes, using UNION function:
SUMMARIZE(
Data,
Data[Category],
"Average",
AVERAGEX(
UNION(
SUMMARIZE(
Data,
Data[Date],
"Sum of Units",
SUM(Data[Units])
),
ADDCOLUMNS(
EXCEPT(
ALL(Data[Date]),
VALUES(Data[Date])
),
"Sum of Units",
0
)
),
[Sum of Units]
)
)

How to compare one row to others in DAX in Excel

I have this table which has foreign keys from several other keys:
Basically, this table shows which students registered in which module run by which teacher in what term.
I want to query the following:
How many students have registered for more than one module run by a given tutor?
It will look something like this:
For example, Vasiliy Kuznetsov runs two modules: FunPro and NO. If one student registers for both of them, he is counted as one.
My sql oriented mind is telling me this: Count all the rows in which student_id and tutor_id are the same. For example, in one row student_id is 5 and tutor_id is 10, and the same is true for the third row. Then, I count it as one.
How can I do that with DAX formulas?
RowCount:=
COUNTROWS( ModuleRegistration )
StudentsWithTwoOrMoreRegistrations:=
COUNTROWS(
FILTER(
VALUES( ModuleRegistration[Student_ID] )
,[RowCount] >= 2
)
)
I refer to arguments positionally, thus the first argument to a function is (1), the second (2), and so on.
So, [RowCount] is trivial.
[StudentsWithTwoOrMoreRegistrations] is a bit more involved. DAX, being a functional language, is best understood inside-out.
FILTER() takes a table expression in (1) and evaluates a boolean predicate, (2), for each row in (1). It returns all rows from (1) for which (2) evaluates to true.
Our FILTER()'s (1) is VALUES( ModuleRegistration[Student_ID] ). VALUES() returns the unique rows from a field based on current filter context (it respects slicers and filters in the pivot table). Thus, we will return some subset of the unique list of [Student_ID]s.
Our FILTER()'s (2) is [RowCount] >= 2. For each [Student_ID] in (1), we'll evaluate [RowCount], checking how many times that student appears in ModuleRegistration. [RowCount] is evaluated in the combination of filter context from the pivot table (the [Faculty Name] field in your sample pivot provides filter context) and row context from FILTER()'s (1). Thus it counts how many times the student appears in ModuleRegistration for the [Faculty Name] on the pivot table row.
We check that [RowCount] is >= 2.
You've not indicated if your measure needs to handle grand totals, or how you might want to see that. If you need more help for the grand total to get it to behave the way you like, let me know.
Edit for grand total
There are a few ways you might want to handle grand totals. I'm gong to assume that you want a unique count of students.
StudentsWithTwoOrMoreRegistrations:=
COUNTROWS(
SUMMARIZE(
FILTER(
SUMMARIZE(
ModuleRegistration
,ModuleRegistration[Tutor_ID]
,ModuleRegistration[Student_ID]
)
,[RowCount] >= 2
)
,ModuleRegistration[Student_ID]
)
)
WTF happened to our measure?
Let's examine:
Starting with the innermost SUMMARIZE(). SUMMARIZE() navigates relationships outward from the table in (1) and groups by the columns listed in (2)-(N) (these don't have to be from the table in (1), but must be reachable by navigating relationships).
This is equivalent to the following in SQL:
SELECT
mr.Tutor_ID
,mr.Student_ID
FROM ModuleRegistration mr
We use FILTER() on this table like earlier. [RowCount] is evaluated in the combination of filter context from the pivot table and the row in the table, defined by our SUMMARIZE() above.
Now our row context is instead of just a student, a student-tutor pair. This pair will have a [RowCount] >= 2 when the student has taken more than one module from a tutor.
Our FILTER() returns the pairs which have a [RowCount] >= 2. This output table has two fields, [Tutor_ID] and [Student_ID], but we want to count distinct [Student_ID]s out of this.
Thus, we use the table from FILTER() as our (1) in the outer SUMMARIZE(). We group only by the values of [Student_ID]. We then count the rows of this table.
When only one [Faculty_Name] is in context, e.g. on a pivot table row, then our inner SUMMARIZE() is grouping by a single value of [Tutor_ID] and whatever [Student_ID]s are associated with it. This is identical to our earlier measure.
When we have many [Tutor_ID]s in context, like in the grand total, then we'll see the appropriate behavior of only counting each [Student_ID] once.

Previous Year row in measurement, DAX formula

I have the following table:
Year test is the list of previous year:
=SUMX(Datasrc;Datasrc[Year]-1)
How do I get something similar for "Calculated field 1"? In other words, I want to get the previous "Price/kg" so it match column C, "Year test".
I have tried with the formula from Find rows relative to current row's value in excel (DAX):
=SUMX(
FILTER(Datasrc; EARLIER([Year]) = [Year] + 1 );
Datasrc[C_Total Asset Per Share]
)
But only get: "Calculation error in measure 'Datasrc'[Calculated field 2]: EARLIER/EARLIEST refers to an earlier row context which doesn't exist."
The column A is [Year]
DAX has time intelligence functions built in, so it's fairly easy to do what you'd like using the SAMEPERIODLASTYEAR function.
First you need a date table joined to your fact table. Then just do
CALCULATE ( [Base Measure], SAMEPERIODLASTYEAR(DateTable[Date]) )

Resources