So basically I have a table where are partners and the dates when then they did their orders.
partner_id | order_date |
---|---|
1 | 2022-01-02 |
1 | 2022-01-20 |
2 | 2022-02-20 |
4 | 2022-01-15 |
4 | 2022-01-17 |
4 | 2022-01-30 |
And I want to have an information of each partner average of purchase period, e.g.
partner_id | period |
---|---|
1 | 18 |
2 | 0 |
4 | 8 |
How do I get these:
1 ID partner – (2022-01-20 – 2022-01-02) / 2
2 ID partner – 0
3 ID partner – avg(2022-01-15 – 2022-01-17) / 2 + (2022-01-17 – 2022-01-30) / 2))
Would it be possible and how to get these intervals?
2
Answers
You just have to do a sub-query where difference between dates is calculated, then the average is calculated, like this:
Working sample here
You can use
lag()
to get the previous date, then aggregate:Note that
lag()
returnsnull
when there is no previous row, whichavg()
then ignores; this seems to be what you want.