This the example of the table name is merchant_point_log :
id created_date merchant_id point_value recent_point status
1 2022-01-02 1 5000 5000 earn
2 2022-01-02 2 3000 3000 earn
3 2022-01-02 1 3000 3000 redeem
i would like to show logging like with previous recent point in one row like :
id created_date merchant_id status previous_point point_value recent_point
1 2022-01-02 1 in 0 5000 5000
2 2022-01-02 1 out 5000 3000 2000
3 2022-01-02 2 in 0 3000 3000
how do i return previos_point column from before row of selected data ?
i already tried this query but still doesn’t work as expected :
select
mpl.id
, mpl2.recent_point as previous_point
, mpl.point_value
, mpl.recent_point
from merchant_point_log mpl
left join merchant_point_log mpl2 on mpl.created_date = adddate(mpl2.created_date, 1)
order by mpl.id asc
;
the result is previous point dont return as expected it always repeat same value. I use mysql version 5.7
2
Answers
We use
lag
to getprevious_point
andcoalesce
to put it as 0 in caseprevious_point
is null
.Fiddle
Here’s an answer with
left join
for older versions where window functions are not an option.Fiddle