Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
9 years ago
Solved

add previous row values

Hi,

 

I have a fact table of sales and I need to get 2 new columns, wich will display Previous date of purchase and Previous sales status (both red in the table below).

 

I'm trying to get same results as with using lag/window function in SQL ( lag(date_of_purchase) over (partition by month_of_sale, customer, product order by date_of_purchase). 

Also, the problem is, I no longer can edit Query (the table in database no longer exists)..

 

month of salecustomerproductsales statusdate of purchaseprevious date of purchaseprevious sales status
Dec-16johnAbooked01-12-16nullnull
Dec-16johnAbooked20-12-1601-12-16booked
Dec-16aliciaApaid01-12-16nullnull
Jan-17johnCk111booked01-01-17nullnull
Jan-17johnCk111paid13-01-1701-01-17booked
Jan-17johnAbooked01-01-17nullnull
Jan-17johnAbooked03-01-1701-01-17booked
Jan-17aliciaCk111booked01-01-17nullnull
Jan-17aliciaCk111paid13-01-1701-01-17booked
Jan-17aliciaCk111paid20-01-1713-01-17paid

 

 

I've been trying to use calculate function with filters, but so far no useful results. I'm new at DAX, so probably I'm not using them right way..

 

Thanks in advance for any help!

Zuzana

  • Hi Anonymous,

     

    You can create calculated columns follow below DAX:

     

    previous date of purchase = CALCULATE(MAX('Table1'[date of purchase]),FILTER(Table1,'Table1'[month of sale]=EARLIER(Table1[month of sale]) && 'Table1'[customer]=EARLIER(Table1[customer])&&'Table1'[product]=EARLIER(Table1[product])&&'Table1'[date of purchase]<EARLIER('Table1'[date of purchase])))

     

    previous sales status = LOOKUPVALUE( Table1[sales status], Table1[month of sale], Table1[month of sale], Table1[customer], Table1[customer], Table1[product], Table1[product], Table1[date of purchase], Table1[previous date of purchase] )

     

     

    Best Regards,
    Qiuyun Yu

3 Replies

  • v-qiuyu-msft's avatar
    v-qiuyu-msft
    Community Support

    Hi Anonymous,

     

    You can create calculated columns follow below DAX:

     

    previous date of purchase = CALCULATE(MAX('Table1'[date of purchase]),FILTER(Table1,'Table1'[month of sale]=EARLIER(Table1[month of sale]) && 'Table1'[customer]=EARLIER(Table1[customer])&&'Table1'[product]=EARLIER(Table1[product])&&'Table1'[date of purchase]<EARLIER('Table1'[date of purchase])))

     

    previous sales status = LOOKUPVALUE( Table1[sales status], Table1[month of sale], Table1[month of sale], Table1[customer], Table1[customer], Table1[product], Table1[product], Table1[date of purchase], Table1[previous date of purchase] )

     

     

    Best Regards,
    Qiuyun Yu