Domanda

In MySQL, I have a table with several columns, one of them being a date column. I want to be able to make a query so i can get an additional column showing the number of days between the current date (the date for each row) and the date of the previous row.

The order of records is by date, and I filter by other column.

e.g.

id  other_col   date        days_between_dates
1   abc     2013-05-01      0
2   abc     2013-05-07      6
3   abc     2013-05-09      2
4   abc     2013-05-19      10
5   abc     2013-05-25      6
6   abc     2013-06-03      9
7   abc     2013-06-14      11

Obviously since the first row has nothing to compare to, it should show 0.

I know i can get the diff between two dates with the datediff MySQL function, e.g.

select datediff('2013-06-03','2013-05-25');

My basic query is select * from mytable where other_col = 'something' order by date; but how can i make a query to directly obtain a result like in the example ? (I need the extra "days_between_dates" column).

Also note that usually the id's are ordered, and without gaps, but i cannot guarantee that. only that i will sort by ascending date, and filtering by the "other_col" column.

È stato utile?

Soluzione

You can do something along these lines:

SELECT T.id, 
       T.other_col, 
       T.yourdate, 
       IFNULL(datediff(T.yourdate,(select MAX(TT.yourdate) 
                                   FROM yourtable TT 
                                   WHERE TT.yourdate < T.yourdate 
                                   AND TT.other_col = 'abc')),0)
FROM yourtable T
where other_col = 'abc';

You can see it in this fiddle

This works by calculating the difference between the current record's date (T.date) and the date that is the biggest (MAX(TT.date)) of the one's that are smaller than the current record's date ( WHERE TT.date < T.date ).

When there is no smaller date, there's the COALESCE to make it be 0, instead of null.

Edit. added coalesce to give 0 in the first line

Altri suggerimenti

I was going to suggest an alternative to the answer given above. If you can guarantee that the id's are sequential, you can join the table to itself to get the result you are looking for:

SELECT t1.id, t1.other_col, t1.date, DATEDIFF(t2.date,t1.date)
FROM table AS t1
LEFT_JOIN table AS t2 ON t1.id = t2.id - 1

Note that I use a LEFT JOIN here such that the first row and last rows on t1 (the main table) will be present.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top