I have a table 'orders' that looks like this:
+---------------+--------------+------------+
| customer_name | order_number | date |
+---------------+--------------+------------+
| jack | 1 | 2018-01-01 |
| jack | 2 | 2018-01-06 |
| jack | 3 | 2018-01-19 |
| jack | 4 | 2018-01-06 |
| jack | 5 | 2018-02-27 |
| jack | 6 | 2018-02-02 |
+---------------+--------------+------------+
Now, I want a table that gives me the difference in the consecutive dates in days. Like so:
+------------+------------+------+
| date | next_date | diff |
+------------+------------+------+
| 2018-01-01 | 2018-01-06 | 5 |
| 2018-01-06 | 2018-01-06 | 0 |
| 2018-01-06 | 2018-01-19 | 13 |
| 2018-01-19 | 2018-02-02 | 14 |
| 2018-02-02 | 2018-02-27 | 25 |
+------------+------------+------+
The query I used is this:
SELECT orders.date, MIN(table1.date) FROM orders
LEFT JOIN orders table1
on orders.customer_name = table1.customer_name
AND table1.date >= orders.date
AND table1.order_number != orders.order_number
WHERE orders.customer_name = 'jack'
GROUP BY orders.order_number, orders.date
ORDER BY orders.date;
This is the ouptput:
+------------+------------+
| date | next_date |
+------------+------------+
| 2018-01-01 | 2018-01-06 |
| 2018-01-06 | 2018-01-06 |
| 2018-01-06 | 2018-01-06 |
| 2018-01-19 | 2018-02-02 |
| 2018-02-02 | 2018-02-27 |
| 2018-02-27 | NULL |
+------------+------------+
As you can see there are a a few issues.
- There are two rows where the
date
andnext_date
are both2018-01-06
. - There is no row where the
next_date
is 2018-01-19` - The last row has a NULL value for
next_date
- How do I get difference in date in days?
I know this is happening because I have grouped by order_number and >=
but I don't know how else to approach this. I feel like there is an obvious easy solution to this that is evading me. Any help?
In case SQL Fiddle doesn't work:
CREATE TABLE orders
(`customer_name` varchar(4), `order_number` int, `date` varchar(10))
;
INSERT INTO orders
(`customer_name`, `order_number`, `date`)
VALUES
('jack', 1, '2018-01-01'),
('jack', 2, '2018-01-06'),
('jack', 3, '2018-01-19'),
('jack', 4, '2018-01-06'),
('jack', 5, '2018-02-27'),
('jack', 6, '2018-02-02')
;