Calculate date difference from previous row of each unique ID in MySQL -


i sql beginner , learning ropes of querying. i'm trying find date difference between purchases same customer. have dataset looks this:

id | purchase_date ================== 1  | 08/10/2017 ------------------ 1  | 08/11/2017 ------------------ 1  | 08/17/2017 ------------------ 2  | 08/09/2017 ------------------ 3  | 08/08/2017 ------------------ 3  | 08/10/2017 

i want have column shows difference in days each unique customer purchase, output this:

id | purchase_date | difference =============================== 1  | 08/10/2017    | null ------------------------------- 1  | 08/11/2017    | 1 ------------------------------- 1  | 08/17/2017    | 6 ------------------------------- 2  | 08/09/2017    | null ------------------------------- 3  | 08/08/2017    | null ------------------------------- 3  | 08/10/2017    | 2 

what best way go using mysql query?

this rather tricky in mysql. best way learn if beginning correlated subquery method:

select t.*, datediff(purchase_date, prev_purchase_date) diff (select t.*,              (select t2.purchase_date               t t2               t2.id = t.id ,                     t2.purchase_date < t.purchase_date               order t2.purchase_date desc               limit 1              ) prev_purchase_date       t      ) t; 

performance should okay if have index on (id, purchase_date).


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -