Difference between two measure dax - powerpivot

I have a measure that calculates previous recorded sales now I would like to work out the difference between period sales against previous period sales, I tried simple subtraction but I get error message..
Any suggestions please..
Thanks
Sales Change:= sales[sales]-Previous Day Sales
Previous Day Sales :=
CALCULATE (
SUM ( Sales[Sales] ),
FILTER (
ALL ( Sales ),
Sales[Date]
= CALCULATE (
MAX ( Sales[Date] ),
FILTER (
ALL ( Sales ),
COUNTROWS ( FILTER ( Sales, EARLIER ( Sales[Date] ) < Sales[Date] ) )
)
)
)
)

If you are creating a measure you have to aggregate the Sales[Sales] using the SUM() function.
Sales Change := SUM(Sales[Sales])-[Previous Day Sales]
While creating measures you cannot refer to column values without an aggregation. Measures run in multiple contexts and the Sales[sales] column value cannot be calculated in a different context than the row context.

Related

Dynamic performance % dax formula

Hope you all are doing well and safe!!
I have a question regarding Power BI dax. I want to create a dax measure for performance percentage in which numerator and denominator will be as per user filter.
Case 1: I want to create a dax measure for performance % (Current Month Sales / Dec'20 Sales) in which current month value will be depending upon user drop down filter and denominator will be fixed with Dec'20 sales value.
Case 2: I want to create a dax measure for performance % (Current Month Sales / Previous Month Sales) in which current month value will be depending upon user drop down filter and denominator will be as per previous month depending upon month selection done by user.
Thanks in advance :)
Try these measures
Case 1 =
DIVIDE (
[Measure],
CALCULATE (
[Measure],
Dates[Calendar Year Number] = 2020,
Dates[Month Number] = 12,
REMOVEFILTERS ( Dates )
)
)
Case 2 =
VAR SelectedMonth =
CALCULATE ( MAX ( Dates[Calendar Year Month Number] ), ALLSELECTED ( Dates ) )
VAR PreviousMonth =
CALCULATE (
MAX ( Dates[Calendar Year Month Number] ),
Dates[Calendar Year Month Number] < SelectedMonth,
REMOVEFILTERS ( Dates )
)
VAR Result =
DIVIDE (
[Measure],
CALCULATE (
[Measure],
Dates[Calendar Year Month Number] = PreviousMonth,
REMOVEFILTERS ( Dates )
)
)
RETURN
Result

Translating SQL with join and window function to DAX

I have a working SQL query, but it needs to be translated to DAX and I'm struggling.
This is what I'm trying to achieve:
I have agreements running from a startdate to an enddate in a fact table. An agreement running for a whole year counts as 1, meaning DATEDIFF(startdate, enddate) / 365.0 gives the "weight" of the agreement. It is needed to look at any given month and get the sum of the trailing year's total agreement weights. I also have a dimension table related to the fact table with all dates (single days and in which year/month they belong), which gives me the possibility to perform the following SQL query to get exactly what I want:
SELECT
sub.yearMonth
,SUM(sub.[cnt]) OVER (ORDER BY sub.[yearMonth] DESC ROWS BETWEEN 11 PRECEDING AND CURRENT ROW) / 365.0 AS [runningYear]
FROM
(SELECT
d.yearMonth
,COUNT(*) AS [cnt]
FROM Agreememts AS a
INNER JOIN Date AS d
ON d.date >= a.startddate AND d.date <= a.enddate
GROUP BY d.yearMonth
) AS sub
I tried to replicate this in a DAX measure ending up with the following:
AgreementWeights:=
CALCULATE (
CALCULATE (
COUNTROWS ( 'Agreements' );
FILTER (
'Agreements';
'Agreements'[startdate] <= MAX ( 'Date'[date] )
&& 'Agreements'[enddate] >= EDATE ( MAX( 'Date'[date] ); -12)
)
);
CROSSFILTER ( 'Agreements'[receiveddate]; 'Date'[sys_date_key]; NONE )
)
The last line is to cut the relationship from the recieveddate to the date dimension, which is irrelevant here. This DAX query yields too many rows, but gives the correct result when divided like (result/365)*100 and I simply cannot figure out why.
An example of the fact table Agreements:
ID startdate enddate recieveddate
0 10-04-2014 12-06-2015 10-03-2014
1 11-06-2014 11-07-2014 11-05-2014
An example of the dimension table Date:
ID date yearMonth sys_date_key
0 10-04-2014 April2014 10042014
1 11-04-2014 April2014 11042014
Thanks :)

I'm trying to calculate the difference between two weeks but I'm getting a weird peak when plotting the results ( SQL / BigQuery )

so I have this daily table that contains the number of visitors per store, everyday.
My tables columns are:
Date
Store
Number_of_Visitors
Views : number of views of the stores' ads.
So I first started with aggregating my table to a weekly table so that I can calculate the variance between a week and the next one.
Here is how I defined variance:
Variance = `Number Of Visitors in WEEK N+1 / Number of Visitors in WEEK N
I wrote the following query to do that (new table called: weekly)
SELECT
year_week,
min(date) as date,
Store,
SUM(Number_Of_Visitors) AS TOTAL_VISITORS
FROM (
SELECT
*,
CONCAT(cast((extract(YEAR from date)), LPAD(cast((extract(WEEK from date)) as string), 2, '0') ) AS year_week
FROM `my-project`)
GROUP BY
year_week, Store
ORDER BY year_week
Then, in order to calculate the variance, I used the following query as well:
SELECT
base.*,
((base.TOTAL_VISITORS-lw.TOTAL_VISITORS)/lw.TOTAL_VISITORS) AS VAR_FF,
FROM
`weekly` base
JOIN (
SELECT
* EXCEPT (date),
DATE_ADD(DATE(TIMESTAMP(date)), INTERVAL 1 Week)AS n_date
FROM
`weekly` ) lw
ON
base.date = lw.n_date
AND base.Store= lw.Store
When I'm plotting the variance (VAR_FF) using Data Studio and I'm getting the following plot that doesnt 't seem to be making sense with the high peak in the middle;
I am thinking your code should look like this:
SELECT date_trunc(date, week) as year_week,
Store,
SUM(Number_Of_Visitors) AS TOTAL_VISITORS,
(1 -
(LAG(SUM(Number_Of_Visitors)) OVER (PARTITION BY Store ORDER BY MIN(date) /
SUM(Number_Of_Visitors)
)
) as VAR_FF,
FROM`my-project`
GROUP BY year_week, Store
ORDER BY year_week;
I'm not sure what your weird calculations for calculating the week are really doing. This is based on the previous week in the data.

MDX YTD Calculated Member for current and parallel period

Trying to build a calculated member using our date hierarchy for use in Tableau.
Hierarchy is as follows:
Fiscal Year
Fiscal Season
Fiscal Quarter
Fiscal Month
Fiscal Week
Date
To help our users with their analysis on dashboards, we're looking to build a Tableau set including the following members for them to toggle through:
Yesterday, Week to Date, Month to Date, Season to Date, and Year to Date.
We need to be able to show Sales $ and Sales $ LY(measure is defined as parallel period) together and be able to toggle through the different "to date" values. The this year portion is fine, but creating a calculated member that works appropriately for the LY measure too has been problematic. We need to be able to pivot between the periods for dashboards rather than create individual measures for each period TY and LY.
Here are the current definitions we have out there:
Yesterday: [DATE].[Time].defaultmember
WTD: [DATE].[Time].defaultmember.parent
MTD: [DATE].[Time].defaultmember.parent.parent
STD: [DATE].[Time].defaultmember.parent.parent.parent
YTD: [DATE].[Time].defaultmember.parent.parent.parent.parent
Any thoughts on how to modify these so that the LY measure reflects the same "to date" period rather than the full period last year?
Count the number of days completed this year and then use the Head function to get the same set of dates from the previous year - aggregate that set together.
Here is an illustration against the AdvWrks cube:
WITH
SET [DaysThisYear] AS
Descendants
(
[Date].[Calendar].[Calendar Year].&[2007]
,[Date].[Calendar].[Date]
)
MEMBER [Measures].[posOfCurrentDate] AS
Rank
(
[Date].[Calendar].CurrentMember
,Descendants
(
[Date].[Calendar].Parent.Parent.Parent.Parent
,[Date].[Calendar].[Date]
)
)
MEMBER [Measures].[prevEquivMTD] AS
Sum
(
Head
(
Descendants
(
[Date].[Calendar].Parent.Parent.Parent.Parent.PrevMember
,[Date].[Calendar].[Date]
)
,[Measures].[posOfCurrentDate]
)
,[Measures].[Internet Sales Amount]
)
MEMBER [Measures].[posCurrentYear] AS
[Date].[Calendar].Parent.Parent.Parent.Parent.Member_Caption
SELECT
{
[Measures].[posCurrentYear]
,[Measures].[posOfCurrentDate]
,[Measures].[Internet Sales Amount]
,[Measures].[prevEquivMTD]
} ON 0
,
[Date].[Calendar].[Date].&[20050111]
:
[Date].[Calendar].[Date].&[20080611] ON 1
FROM [Adventure Works];
This is the above as a single measure:
WITH
MEMBER [Measures].[Internet Sales Amount prevEquivMTD] AS
Sum
(
Head
(
Descendants
(
[Date].[Calendar].Parent.Parent.Parent.Parent.PrevMember //previous year
,[Date].[Calendar].[Date]
)
,Rank
(
[Date].[Calendar].CurrentMember
,Descendants
(
[Date].[Calendar].Parent.Parent.Parent.Parent //current year
,[Date].[Calendar].[Date]
)
)
)
,[Measures].[Internet Sales Amount]
)
SELECT
{
[Measures].[Internet Sales Amount]
,[Measures].[Internet Sales Amount prevEquivMTD]
} ON 0
,
[Date].[Calendar].[Date].&[20050111]
:
[Date].[Calendar].[Date].&[20080611] ON 1
FROM [Adventure Works];
Unfortunately it is tied to the measure Internet Sales Amount so not very generic. Generic calcs such as prev equiv mtd or Year on Year growth are usually added to a helper Time Caculation helper dimension that is independent from the Date dimension.

Weekly/monthly/quarterly grouping in query

Lets say I have table with following columns
1. Client - string.
2. Profit - integer.
3. Deal_Date - date.
I need query that will retrieve sum of profit breakdown by week/month/quater etc.
Expected output for weeks
1 row, sum (profit) of all deals that registered from (03.19.2012 - 03.12.2012).
2 row, sum (profit) of all deals that registered from (03.12.2012 - 03.05.2012).
...
n row, sum (profit) of all deals that registered from (05.17.2011 - 05.10.2011).
NOTE (dates set just for example)
The same for month, years, etc.
Could someone help me with such query?
Btw performance is very important.
This query uses simple date formats to extract the various elements you want to track and analytics to get the sums.
select client
, yr
, qtr
, wk
, sum ( profit ) over ( partition by client, yr) as yr_profit
, sum ( profit ) over ( partition by client, yr, qtr) as qtr_profit
, sum ( profit ) over ( partition by client, yr, wk) as wk_profit
from (
select client
, profit
, to_char(deal_date, 'yyyy') as yr
, to_char(deal_date, 'q') as qt
, to_char(deal_date, 'ww') as wk
from your_table )
/
This will produce one row for each row in the current table. So you probebly will want to wrap it in a further outer query which only returns only distinct rows.
A variant would be to use rollup instead. I'm not sure how well that works when the grouping criteria aren't perfectly hierarchical (weeks don't fit neatly into quarters).
select client
, yr
, qtr
, wk
, sum ( profit ) as profit
from (
select client
, profit
, to_char(deal_date, 'yyyy') as yr
, to_char(deal_date, 'q') as qt
, to_char(deal_date, 'ww') as wk
from your_table )
group by rollup ( client, yr, qtr, wk )
/
Just make an SP and loop the code for each week or month or year as you wish.