Hey! Can you help me out? I’m trying to create a m...
# gd-beginners
t
Hey! Can you help me out? I’m trying to create a metric that shows: • Current purchase: invoice, item, value, date. • The last purchase value for the same item. The issue is my metric just repeats the current value instead of pulling the previous one. Any ideas how to fix this? Thanks!
m
Hi Tomas, Using the For Previous functionality, you're able to access data of the previous row, or the row before the previous row, and so on. I recommend checking the following documentation for more details: https://help.gooddata.com/classic/en/dashboards-and-insights/maql-analytical-query-la[…]se-cases-and-tutorials/time-over-time-comparison-in-reports/
m
Hi Tomas, I am afraid FOR PREVIOUS will not work here, since it shifts the event in time (i.e. it shifts it to another month or quarter) but if I understand it correctly, that is not what you want, you want to get a value of previous purchase within some group, no matter how long time ago it happened. Basically what a LAG function would od in SQL? MAQL does not have LAG function but if you want to get previous value based on date (which I believe you do) you can emulate this behavior by using a running total function with specified window function. Specifically you can write this MAQL:
SELECT RUNMIN(metric) WITHIN (attribute, ALL OTHER) ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING
and it will do what this SQL would do:
Copy code
SELECT LAG(metric) OVER PARTITION BY attribute ORDER by Date
basically give you a previous (based on the Date) value of the metric and you can use WITHIN to specify the group within which you want the previous value (i.e. previous order of the same customer or of the same product). This will work when used with a date dimension in a report (or inside another metric with
BY Date, ALL OTHER
). If you ever needed the next value (i.e. SQL function LEAD) just change it to
ROWS BETWEEN 1 FOLLOWING and 1 FOLLOWING
🙌 1