How to Calculate Sum untill start of month of a given date in DAX - powerpivot

I would like to calculate Sum(QTY) until the start date of the month for a given date.
Basically I can calculate Sum(QTY) until given date in my measure like:
SumQTYTillDate:=CALCULATE(SUM([QTY]);FILTER(ALL(DimDateView[Date]);DimDateView[Date]<=MIN(DimDateView[Date])))
But I also would like to calculate Sum(QTY) for dates before 10/1/2015 - which is the first date of selected Date's month. I have changed above measure and used STARTOFMONTH function to find first day of the month for a given date like;
.......DimDateView[Date]<=STARTOFMONTH(MIN(DimDateView[Date]))))
but not avail, it gives me
"A function ‘MIN’ has been used in a True/False expression that is
used as a table filter expression. This is not allowed."
What am I missing? How can I use STARTOFMONTH function in my measure?
Thanks.

STARTOFMONTH() must take a reference to a column of type Date/Time. MIN() is a scalar value, not a column reference. Additionally, your measure wouldn't work, because STARTOFMONTH() is evaluated in the row context of your FILTER(). The upshot of all this is that you would get a measure which just sums [QTY] across the first of every month in your data.
The built in time intelligence functions tend to be unintuitive at best. I always suggest using your model and an appropriate FILTER() to get to what you want.
In your case, I'm not entirely sure what you're looking for, but I think you want the sum of [QTY] for all time before the start of the month that the date you've selected falls in. In this case it's really easy to do. Add a field to your date dimension, [MonthStartDate], which holds, for every date in the table, the date of the start of the month it falls in. Now you can write a measure as follows:
SumQTY=SUM(FactQTY[QTY])
SumQTYTilStartOfMonth:=
CALCULATE(
[SumQTY]
;FILTER(
ALL(DimDateView)
;DimDateView[Date] < MIN(DimDateView[MonthStartDate])
)
)

Related

How to create weekly YoY metric in AWS QuickSight?

I am trying to calculate a sum of a column for a specific calendar week, and want to compare that to the same week in the previous year.
So let's say I have the sum of WK21 for 2020 is 1000 and sum of WK21 in 2019 is 800. The field should return: 200.
Attached is how my dataset looks like.
I would like to sum the credit per WK for each segment, and see how the difference is to the sum of that week for that same segment, in the previous year. Later on I would change the difference to percentDifference, but I assume the main formula is the same.
Is that easy doable?
Tried this (percentDifference) for WoW (in the same year), and it worked using this formula:
percentDifference(sum({credit}),[{wk} ASC],-1,[{year}, industry, segment])
But when trying for weekly YoY the following formula, it didnt work (-52 because 52 weeks in year):
percentDifference(sum({credit}),[{wk} ASC, year ASC],-52,[industry, segment])
PS: for the country, I didnt take that in consideration, as I want to filter for the countries I want later on...
For Year-on-year difference create a calculated field like the following
difference(sum({credit}), [{wk} ASC, {year} ASC], -1, [{Industry}, {Segment}])
For year-on-year percentage difference your calculated field would be
percentDifference(sum({credit}), [{wk} ASC, {year} ASC], -1, [{Industry}, {Segment}])
This is because the lookup index in the function (-1) is based on the sort of the rows (sort order in the square brackets in the function)
Source: percentDifference and difference QuickSight Docs
Try -100 instead of -52. Since the 'wk' field is not a date-defined field, it is probably just considering 'wk' as an int.

Creating a DAX pattern that counts days between a date field and a month value on a chart's x-axis

I am struggling with a DAX pattern to allow me to plot an average duration value on a chart.
Here is the problem: My dataset has a field called dtOpened which is a date value describing when something started, and I want to be able to calculate the duration in days since that date.
I then want to be able to create an average duration since that date over a time period.
It is very easy to do when thinking about the value as it is now, but I want to be able to show a chart that describes what that average value would have been over various time periods on the x-axis (month/quarter/year).
The problem that I am facing is that if I create a calculated column to find the current age (NOW() - [dtOpened]), then it always uses the NOW() function - which is no use for historic time spans. Maybe I need a Measure for this, rather than a calculated column, but I cannot work out how to do it.
I have thought about using LASTDATE (rather than NOW) to work out what the last date would be in the filter context of any single month/quarter/year, but if the current month is only half way through, then it would probably need to consider today's date as the value from which to subtract the dtOpened value.
I would appreciate any help or pointers that you can give me!
It looks like you have a table (let's call it Cases) storing your cases with one record per case with fields like the following:
casename, dtOpened, OpenClosedFlag
You should create a date table with on record per day spanning your date range. The date table will have a month ending date field identifying the last day of the month (same for quarter & year). But this will be a disconnected date table. Don't create a relationship between the Date on the Date table and your case open date.
Then use iterative averagex to average the date differences.
Average Duration (days) :=
CALCULATE (
AVERAGEX ( Cases, MAX ( DateTable[Month Ending] ) - Cases[dtopened] ),
FILTER ( Cases, Cases[OpenClosedFlag] = "Open" ),
FILTER ( Cases, Cases[dtopened] <= MAX ( DateTable[Month Ending] ) )
)
Once you plot the measure against your Month you should see the average values represented correctly. You can do something similar for quarter & year.
You're a genius, Rory; Thanks.
In my example, I had a dtClosed field rather than an Opened/Closed flag, so there was one extra piece of filtering to do to test if the Case was closed at that point in time. So my measure ended up looking like this:
Average Duration:=CALCULATE(
AVERAGEX(CasesOnly, MAX(DT[LastDateM]) - CasesOnly[Owner Opened dtOnly]),
FILTER(CasesOnly, OR(ISBLANK(CasesOnly[Owner Resolution dtOnly]),
CasesOnly[Owner Resolution dtOnly] > MAX(DT[LastDateM]))),
FILTER(CasesOnly, CasesOnly[Owner Opened dtOnly] <= MAX(DT[LastDateM]))
)
And to get the chart, I plotted the DT[Date] field on the x-axis.
Thanks very much again.

Referencing a measure in DAX DATESBTWEEN function

In Powerpivot 2013 I am trying to calculate unit sales per day between the last time an item was received and the last time it was sold, but I keep getting tripped up by the DATESBETWEEN fuction.
These measures return the dates of of the last recieve and last sale:
Lastsale:=CALCULATE(LASTDATE(InvDetail[Date]), InvDetail[Type]="Sale")
Lastrecv:=CALCULATE(LASTDATE(InvDetail[Date]), InvDetail[Type]="Receive", all(InvDetail[Date]))
This is what I'm using to get the units sold between the last receive and last sale, but it's not working. I don't get an error, just crazy big numbers.
UnitsSold:=calculate(sum(InvDetail[units]), InvDetail[Type]="Sale", DATESBETWEEN(InvDetail[Date], [Lastrecv], [Lastsale]))
If I hard-code in the dates as below, it works.
UnitsSold:=calculate(sum(InvDetail[units]), InvDetail[Type]="Sale", DATESBETWEEN(InvDetail[Date], date(2015,1,1), date(2015,2,1)))
I also have to get the number of dates in that date range too, but I haven't gone there yet.
Is there some reason why I can't use the measures in the DATESBETWEEN function?
It's tricky without the data but my guess is that inside the DATESBETWEEN() you just aren't getting the expected filter context.
The first thing I would try is incorporating the measures in a CALCULATE() with a FILTER():
= CALCULATE(SUM(InvDetail[units]),
InvDetail[Type]="Sale",
FILTER(ALL(InvDetail[Date]),
InvDetail[Date] >= [Lastrecv] &&
InvDetail[Date] <= [Lastsale]
)
)
You could adapt this to count your dates with a DISTINCTCOUNT() on the date column instead of summing the units.

Average of DATE field in Teradata

I have a column of data in [DATE] format. It is a record of the first time an order was purchased. I am attempting to query the average date in this column. Meaning, I want to know what the average "first purchase" is.
Purchase_dt
01-01-2014
02-01-2014
03-05-2014
I need something to show what the average purchase_dt is.
Cheers
You can use a AVG on a DATE column, in fact it's using the same algorithm Tripp Kinetics mentioned. But it's probably using an INT as intermediate result, which soon results in a "numeric overflow"
For a larger number of rows you'll need to do the calculation manually like:
DATE '1900-01-01' + CAST(AVG(CAST(trans_date-DATE '1900-01-01'AS BIGINT)) AS INT)

Filtering a Dimension Relative to a CurrentMember in MDX

I'm having a bit of trouble accomplishing something that I think should be relatively straightforward in MDX. I would like to create a calculated member that provides a sum of one of my measures over the previous two weeks at a given point in time. My time dimension looks like:
TimeId TradingDate Day of Week
-----------------------------------
1000 11/1/2012 Thursday
1001 11/2/2012 Friday
1002 11/5/2012 Monday
1003 11/6/2012 Tuesday
... ...
What makes this particularly difficult is that my Time dimension is not quite complete. The members of my Time dimension only correspond to trading days in the stock market, and not all time. This means that weekends, holidays, or any other day in which the stock market is closed are excluded. This also means the normal methods of traversing time such as LAG or PARALLELPERIOD will not work quite right here. LAG(14), for example, means "14 trading days", which at any given point could represent a variable length of actual time.
Inside my calculated member, I'm attempting to use FILTER in order to get only time members that are within the previous two weeks of the CurrentMember. However, I can't seem to figure out the proper syntax (if there is one) to accomplish this. I imagine it would be something like:
WITH MEMBER [Sum of Price Previous 2 Weeks] AS
SUM(
FILTER(
[Time].[TimeId].Children
, [Time].[TradingDate].MemberValue
>= VBA!DATEADD("ww", -2, [Time].[TradingDate].CurrentMember.MemberValue)
)
, [Price]
)
However, this doesn't quite work. I can't seem to separate the context of the calculated members current iteration from what would be a separate context inside of the FILTER function. In other words, I'm not sure how to say:
"When iterating over the set inside of FILTER, compare the current
member of each iteration against the value of the CurrentMember in
the scope of the calculated member"
Is what I'm trying to accomplish even possible? Is there a different approach I could be taking to accomplish what I'm after?
The result you'll get from a calculated member will depend on the axis of your query. So first, make sure you have [Time].[TradingDate] in your axis.
Second, your [Time].[TradingDate] hierarchy should be ordered by Key (I assume TradingDate is the key).
Now you can use this member definition:
WITH MEMBER [Sum of Price Previous 2 Weeks] AS
SUM(
[Time].[TradingDate].CurrentMember.Lag(14):[Time].[TradingDate].CurrentMember, [Price]
)
You can use set aliases to refer to the outer CurrentMember in the Filter context:
WITH MEMBER [Sum of Price Previous 2 Weeks] AS
SUM(
GENERATE([Time].[TradingDate].CurrentMember AS CurrentDateAlias,
FILTER(
[Time].[TimeId].Children
, [Time].[TradingDate].MemberValue
>= VBA!DATEADD("ww", -2, CurrentDateAlias.Item(0).MemberValue)
)
)
, [Price]
)
GENERATE is used just to define the alias somewhere.