1

I would appreciate help with a table that is looking like this:

  client_id | transaction_date | amount
  -------------------------------------
      123   |     2017-01-16   |   12
      234   |     2017-01-11   |   25 
      345   |     2017-01-12   |  211

I want to get the average for a period of time that the same client did next transaction - in other words - what was the avg number of days that led to the next transaction for certain user?

I was thinking of some TIMESTAMPDIFF, but no idea how to implement that in this case.

Salman A
  • 262,204
  • 82
  • 430
  • 521
Jak To
  • 13
  • 2

2 Answers2

0

Do it something like this

SELECT client_id,avg(DATEDIFF(transaction_date,next_transaction_date)) FROM
(
    SELECT 
    client_id,
    transaction_date ,
    LEAD(transaction_date,1) OVER (
        PARTITION BY client_id
        ORDER BY transaction_date) next_transaction_date
    FROM 
    table    
) as s WHERE next_transaction_date is not null

Here is reference link for the understanding of LEAD function

http://www.mysqltutorial.org/mysql-window-functions/mysql-lead-function/

NoobX
  • 125
  • 6
0

The simplest method is to take the difference between maximum and minimum and divide by one less than the number of rows.

So:

select client_id,
       ( datediff(max(transaction_date), min(transaction_date)) /
         nullif(count(*) - 1, 0)
       ) as avg_duration
from t
group by client_id;

Because your are dealing with dates, you can use datediff() rather than timestampdiff() (saves you on a function argument).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786