问题
I have these two columns: SALES_CALLSID QFQ4TA5006C2 QZPIOA18LW8A QS4GSA300PU0 ....; and MEETING_DATE 7/10/2014 12:00 3/27/2015 12:00 11/3/2015 12:00
I need the count of the first column (salesid) but this count should be a trailing twelve month average for every month, i.e. for example for July- the count of sales id of july + count of last 11 months (i.e. based on the meeting date column), similarly this measure has to be made for every other month.
The "Sales Call ID" column is a text field. I can see the count using the formula COUNTA(AccountSalesCalls[SALES_CALLSID])`.
The formula i built to get the total count of sales id for last 12 months is as follows:
CALCULATE (
COUNTA ( AccountSalesCalls[SALES_CALLSID] ),
DATESBETWEEN (
AccountSalesCalls[MEETING_DATE],
NEXTDAY ( SAMEPERIODLASTYEAR ( LASTDATE ( AccountSalesCalls[MEETING_DATE] ) ) ),
LASTDATE ( AccountSalesCalls[MEETING_DATE] )
)
)
When i do this i get an error:
A date column containing duplicate dates was specified in the call to function 'DATESBETWEEN'. This is not supported.
I then built a DATE table and replaced MEETING_DATE column with column in DATE table as follows:
CALCULATE (
COUNTA ( AccountSalesCalls[SALES_CALLSID] ),
DATESBETWEEN (
'Date'[Date],
NEXTDAY ( SAMEPERIODLASTYEAR ( LASTDATE ( AccountSalesCalls[MEETING_DATE] ) ) ),
LASTDATE ( AccountSalesCalls[MEETING_DATE] )
)
)
This just gives me the count of that month which is the same result as COUNTA(AccountSalesCalls[SALES_CALLSID])
.
I still haven't done the division part to get the average but first wanted to figure out how to make the total count work. Any help would be appreciated.
回答1:
You were nearly there.
The calculated column:
Average = CALCULATE (
COUNTA ( AccountSalesCalls[SALES_CALLSID] ) / 12,
DATESBETWEEN(
AccountSalesCalls[MEETING_DATE],
DATEADD(AccountSalesCalls[MEETING_DATE], -12, MONTH),
AccountSalesCalls[MEETING_DATE]
),
ALL(AccountSalesCalls)
)
Note this divides by a constant (12), which would be incorrect for the first year of your data. You will have to decide how to deal with this (if at all).
One option could be to divide by the date range of existing selected data instead:
Average = CALCULATE (
COUNTA ( AccountSalesCalls[SALES_CALLSID] ) /
DATEDIFF( MIN(AccountSalesCalls[MEETING_DATE] ),
MAX( AccountSalesCalls[MEETING_DATE] ),MONTH),
DATESBETWEEN(...
More or moving averages using DAX
回答2:
Instead of dividing by 12, I have seen Rob Collie handle the division by
COUNTROWS ( VALUES ( 'Date'[Year-Month] ) )
where [Year-Month] is a calculated column in the 'Date' table:
= FORMAT ( 'Date'[Date], "YYYY-mm" )
Using VALUES in this way also handles cases where the available data covers less than 12 months.
I have also seen Chandoo use a similar approach, but using the COUNTROWS to check if there are twelve months available to base the rolling average on (and if not, return blank).
来源:https://stackoverflow.com/questions/38774048/rolling-month-average-in-power-bi-dax