Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select difference between row dates in MySQL

Tags:

sql

mysql

I want to calculate the difference in unique date fields between different rows in the same table.

For instance, given the following data:

   id | date
   ---+------------
    1 | 2011-01-01
    2 | 2011-01-02
    3 | 2011-01-15
    4 | 2011-01-20
    5 | 2011-01-10
    6 | 2011-01-30
    7 | 2011-01-03

I would like to generate a query that produces the following:

id | date       | days_since_last
---+------------+-----------------
 1 | 2011-01-01 | 
 2 | 2011-01-02 |  1
 7 | 2011-01-03 |  1
 5 | 2011-01-10 |  7
 3 | 2011-01-15 |  5
 4 | 2011-01-20 |  5
 6 | 2011-01-30 | 10

Any suggestions for what date functions I would use in MySQL, or is there a subselect that would do this?

(Of course, I don't mind putting WHERE date > '2011-01-01' to ignore the first row.)

like image 780
Mike S. Avatar asked Sep 10 '11 23:09

Mike S.


1 Answers

A correlated subquery could be of help:

SELECT
  id,
  date,
  DATEDIFF(
    (SELECT MAX(date) FROM atable WHERE date < t.date),
    date
  ) AS days_since_last
FROM atable AS t
like image 184
Andriy M Avatar answered Oct 06 '22 01:10

Andriy M