PowerBi: Days between purchase on multiple rows - powerbi

I'm trying to calculate the daydiff between when the first (H1) and the second (H2) product have been bought for each customer (ID)
I can do it if the dates are on the same line, but not on mulitple rows. There are 5.6mil rows in all with 30 different products, but right now its only between H1 and H2
The result i'm after is something like

For a data source with 5.6M rows, I would only recommend doing it though native server-side query unless the calculations are not required to evaluate in respect to some filter context. Else, you can do it through the following DAX measure.
If you have a table like this and you want the DateDIff by ID for each preceding PurchaseDate
| ID | Product | PurchaseDate |
|----|---------|--------------|
| 10 | H1 | 2021-09-15 |
| 10 | H2 | 2021-09-19 |
| 20 | H1 | 2021-05-01 |
| 20 | H2 | 2021-06-05 |
| 20 | H3 | 2021-07-08 |
you can write the following measure
Measure =
VAR _curentlyVisibleDateById =
MAX ( 'fact'[PurchaseDate] )
VAR _immediatelyPrecedingDateById =
CALCULATE (
CALCULATE (
MAX ( 'fact'[PurchaseDate] ),
'fact'[PurchaseDate] < _curentlyVisibleDateById
),
ALLEXCEPT ( 'fact', 'fact'[ID] )
)
VAR _diffbyId =
DATEDIFF ( _immediatelyPrecedingDateById, _curentlyVisibleDateById, DAY )
RETURN
_diffbyId
Edit
If you want to limit calculations to only specific groups of Product; i.e. only for Products H1,H2,H3 then please use this
Measure =
VAR _curentlyVisibleDateById =
CALCULATE (
MAX ( 'fact'[PurchaseDate] ),
'fact'[Product] IN { "H1", "H2", "H3" }
)
VAR _immediatelyPrecedingDateById =
CALCULATE (
CALCULATE (
MAX ( 'fact'[PurchaseDate] ),
'fact'[PurchaseDate] < _curentlyVisibleDateById
),
ALLEXCEPT ( 'fact', 'fact'[ID] ),
'fact'[Product] IN { "H1", "H2", "H3" }
)
VAR _diffbyId =
DATEDIFF ( _immediatelyPrecedingDateById, _curentlyVisibleDateById, DAY )
RETURN
_diffbyId

Related

How to get a measure of Average of column percentage using DAX in Power BI for column chart?

I am struggling with a problem as follows:
I need a DAX measure to find the average percentage from a matrix table result.
This is what I get from the matrix table in Power BI
Place Late No-Late Total
India 2 200 202
Bangladesh 40 60 100
China 0 150 150
Total 42 410 452
Then I apply % of Row Total
Place Late No-Late Total
India 1% 99% 100%
Bangladesh 40% 60% 100%
China 0 100% 100%
Total 9% 91% 100%
Now I need the average percentage from the "No-Late" Column which will be "86%" to plot it in the column chart.
How can I achieve this part?
Can you please try the following
_avg =
VAR _0 =
SUMX (
'fct',
VAR _total = fct[Late] + fct[No-Late]
VAR _noLate = fct[No-Late]
VAR _pct =
DIVIDE ( _noLate, _total )
RETURN
_pct
)
RETURN
DIVIDE ( _0, DISTINCTCOUNT ( fct[Place] ) )
Edit
if you want to display the total in a chart like below
please make sure your data source is like following. Because for Total to be displayed in a chart, the axis must present in the data source itself.
| Place | Late | No-Late | Index |
|------------|------|---------|-------|
| India | 2 | 200 | 1 |
| Bangladesh | 40 | 60 | 2 |
| China | 0 | 150 | 3 |
| Total | null | null | 4 |
and then you can write following measure
_avg2 =
VAR _currentlyVisiblePlace =
MAX ( fct[Place] )
VAR _aggregation =
SWITCH (
TRUE (),
_currentlyVisiblePlace <> "Total",
VAR _0 =
SUMX (
'fct',
VAR _total = fct[Late] + fct[No-Late]
VAR _noLate = fct[No-Late]
VAR _pct =
DIVIDE ( _noLate, _total )
RETURN
_pct
)
VAR _1 =
DIVIDE ( _0, DISTINCTCOUNT ( fct[Place] ) )
RETURN
_1,
_currentlyVisiblePlace = "Total",
VAR _0 =
SUMX (
ALL ( fct ),
VAR _total = fct[Late] + fct[No-Late]
VAR _noLate = fct[No-Late]
VAR _pct =
DIVIDE ( _noLate, _total )
RETURN
_pct
)
VAR _1 =
DIVIDE (
_0,
CALCULATE (
DISTINCTCOUNT ( fct[Place] ),
ALL ( fct ),
NOT fct[Place] IN { "Total" }
)
)
RETURN
_1
)
RETURN
_aggregation
Let's assume your table looks like the one below where the last three columns are calculated (just the sum and then the percentage)
By adding the following measures
No Late (%) = If( HASONEVALUE(Table1[No-Late (%)]),Table1[Total No Late]/Table1[Total], AVERAGE(Table1[No-Late (%)]))
Total No Late = sum(Table1[No-Late])
you will be able to get the following result in Power BI with the matrix visual

How to calculate percentage using filters in DAX in Power BI?

I have two columns
CustomerCode | Segmentation
AU656 | abc
AU765 | cdf
AU563 | abc
AU235 | abc
AU324 | opr
AU908 | opr
AU123 | pqr
AU234 |pqr
I have to find a distinct count of CustomerCode where segmentation is "abc" and "cdf" and "pqr" and divide it by the total number of CustomerCodes (all).
I created a measure -
#RSP =
CALCULATE (
DISTINCTCOUNT ( 'Table'[CustomerCode] ),
FILTER ( ALL ( 'Table' ), 'Table'[Segmentation] = "abc" ),
'Table'[Segmentation] = "cdf",
'Table'[Segmentation] = "opr"
)
However, this shows no value. Am I using the filters wrong?
How do I calculate this?
Your measure fails because Segmentation cannot be multiple values simultaneously. Try this instead:
#RSP =
CALCULATE (
DISTINCTCOUNT ( 'Table'[CustomerCode] ),
'Table'[Segmentation] IN { "abc", "cdf", "opr" }
)
Ratio = DIVIDE ( [#RSP], DISTINCTCOUNT ( 'Table'[CustomerCode] ) )
In your data You don't have a customer with that specific condition: segmentation is "abc" and "cdf" and "pqr" (Any of the rows doesn't match this). You should use IN (also you can use OR)
#RSP =
CALCULATE(DISTINCTCOUNT('Table'[CustomerCode]),FILTER(ALL('Table'),'Table'[Segmentation] in ("abc","cdf","opr")))
IF you want to find customers, that have rows with more than one segmentation code:
#RSP_2 =
var __custSeg1 = filter('Table'[CustomerCode], TREATAS({"abc"},
'Table'[Segmentation])
var __custSeg2 = filter('Table'[CustomerCode], TREATAS({"cdf"},
'Table'[Segmentation])
var __custSeg2 = filter('Table'[CustomerCode], TREATAS({"opr"},
'Table'[Segmentation])
return
calculate(DISTINCTCOUNT('Table'[CustomerCode]), __custSeg1 ,__custSeg2
,__custSeg2 )

Power BI DAX summarize and filter by date

I have a Power BI report and I want to find the last date some action took place that had a non-0 value. In the following example:
|-------------|------------|
| ActionDate | ActionAmt|
|-------------|------------|
| 1-Feb | -100 |
|-------------|------------|
| 1-Feb | 100 |
|-------------|------------|
| 10-Jan | 150 |
|-------------|------------|
I want to return the 10-Jan date, not 1-Feb, since 10-Jan is the first non-0 value summed by ActionDay. My code returns 1-Feb:
Last Action Date =
VAR maxdatekey =
CALCULATE ( MAX ( 'Action'[ActionDateKey] ), 'Action'[ActionAmount] > 0 )
RETURN
IF (
maxdatekey,
FORMAT (
LOOKUPVALUE ( 'Date'[DateValue], 'Date'[DateKey], maxdatekey ),
"dd-MMM-yyyy"
)
)
How do I further group this to exclude the summarized 0 days?
I think you're looking for something like this where you summarize by date when calculating the amount:
LastActionDate =
VAR Summary =
SUMMARIZE (
'Date',
'Date'[DateValue],
"Amt", CALCULATE ( SUM ( 'Action'[ActionAmount] ) )
)
RETURN
FORMAT (
MAXX ( FILTER ( Summary, [Amt] > 0 ), 'Date'[DateValue] ),
"dd-MM-yyyy"
)

finding the row with earliest date for each customerID who purchased specific product and return the date in new column

I'm working with PowerBI and have the following table:
customer_id|item_id| date
1 | A | 01/01/01
1 | B | 01/01/01
1 | A | 02/02/02
1 | A | 03/03/03
2 | A | 03/03/03
2 | C | 03/03/03
...
I would like to find the earliest date for each customer_id who purchased item A and return 1 in a new column. So that I get a new column in the table that looks like the following:
customer_id | item_id | date | Column_want
1 | A | 01/01/01 | 1
1 | B | 01/01/01 | blank
1 | A | 02/02/02 | blank
1 | A | 03/03/03 | blank
2 | A | 03/03/03 | 1
2 | C | 03/03/03 | blank
...
I've tried to filter the column by item A and then using TOPN(1,...) to choose only the top rows. However, it doesn't seem to work.
This seems like such a trivial request. Is there any smarter way around this?
It's possible to use TOPN for this but that function returns an entire row of a table so it looks pretty clunky like this:
Column_want =
IF (
Table1[item_id] = "A" && Table1[date]
= SELECTCOLUMNS (
TOPN (
1,
FILTER (
Table1,
Table1[item_id] = "A"
&& Table1[customer_id] = EARLIER ( Table1[customer_id] )
),
Table1[date], ASC
),
"date", Table1[date]
),
1
)
I'd suggest something more like this:
Column_Want =
IF (
Table1[date]
= CALCULATE (
MIN ( Table1[date] ),
FILTER (
ALLEXCEPT ( Table1, Table1[customer_id], Table1[item_id] ),
Table1[item_id] = "A"
)
),
1
)
Or this:
Column_Want =
IF (
Table1[date]
= MINX (
FILTER (
Table1,
EARLIER ( Table1[item_id] ) = "A"
&& Table1[customer_id] = EARLIER ( Table1[customer_id] )
),
Table1[date]
),
1
)
You could create a calculated column using variables:
Column_want =
VAR Customer_id ='Table'[customer_id]
VAR Earliest_date = CALCULATE(MIN('Table'[date]),
FILTER('Table','Table'[customer_id]=Customer_id))
VAR Earliest_item = CALCULATE(MIN('Table'[item_id]),
FILTER('Table','Table'[date]=Earliest_date),
FILTER('Table','Table'[customer_id]=Customer_id))
RETURN IF('Table'[date]=Earliest_date && 'Table'[item_id]=Earliest_item,
1,BLANK())
The idea is to calculate the earliest date for a particular Customer ID using Calculate and max (Earliest_date variable). Earliest_Item variable is calculated to avoid multiple records for the same customer getting tagged as 1. Hope this helps.

Power BI DAX Calculating Last week Sales for All the Filter Options

I have following Data Structure
Date | Category | Sales Amount
----------------------------------------------------
01-Sep-2016 | Food | 100
02-Sep-2016 | Food | 120
03-Sep-2016 | Food | 130
01-Sep-2016 | Electricity | 180
02-Sep-2016 | Electricity | 60
01-Sep-2016 | Perfumes | 80
02-Sep-2016 | Perfumes | 40
I want to calculate the Two Week Sales for Each Category, I might add another column like Territory as well in the future. I used following Formula which worked fine if I only select Date but Does Not Work if I select Category.
SalesTwoWeeksAgo =
CALCULATE (
SUM ( 'Table'[SalesAmount] ),
FILTER (
ALL ( 'Table' ),
COUNTROWS (
FILTER (
'Table',
EARLIER ( 'Table'[Date] ) = DATEADD ( 'Table'[Date], -14, DAY )
)
)
)
)
The Above Formula was contributed by alejandro zuleta and link is
Power BI getting 2 week back same day value
If I understand your question, the problem is that you have a Category column so you need to get the sales two weeks back in the time in the current category value evaluated in the expression. You just have to add an additional condition in the FILTER function to take the current Category and the current Date substracting 14 days, then it will return the related Sales Amount values to the SUM function.
SalesTwoWeeksAgo =
CALCULATE (
SUM ( 'Table'[Sales Amount] ),
FILTER (
ALL ( 'Table' ),
COUNTROWS (
FILTER (
'Table',
EARLIER ( 'Table'[Date] ) = DATEADD ( 'Table'[Date], -14, DAY )
&& 'Table'[Category] = EARLIER ( 'Table'[Category] )
)
)
)
)
Also if you add Territory column to your table you may need to get the Sales Amount two weeks before per Date, Category and Territory so you just need to add a third conditional in the FILTER function.
SalesTwoWeeksAgo =
CALCULATE (
SUM ( 'Table'[Sales Amount] ),
FILTER (
ALL ( 'Table' ),
COUNTROWS (
FILTER (
'Table',
EARLIER ( 'Table'[Date] ) = DATEADD ( 'Table'[Date], -14, DAY )
&& 'Table'[Category] = EARLIER ( 'Table'[Category] )
&& 'Table'[Territory] = EARLIER ( 'Table'[Territory] )
)
)
)
)
The solution provided here is not tested yet but hopefully it is what you need.
Let me know if this helps.