I have a table with date ranges. I want to look for gaps between these ranges. I've figured out that I may left join table to itself and calculate the difference.
Current table:
date_begin date_end
2010-08-01 2010-08-15
2010-08-16 2010-08-30
2010-08-31 2010-09-12
2010-10-01 2010-10-15
I want to get:
date_begin date_end - date_begin2 DATEDIFF(date_begin2 - date_end)
2010-08-01
2010-08-01 2010-08-15 2010-08-16 ...
2010-08-16 2010-08-30 2010-08-31 ...
2010-08-31 2010-09-12 2010-10-01 ...
2010-10-01 2010-10-15
I use the following query:
SELECT pay1.date_begin, pay1.date_end,
pay2.date_begin, pay2.date_end, DATEDIFF( pay2.date_begin, pay1.date_end)
FROM `payment_employees` AS pay1
LEFT JOIN `payment_employees` AS pay2 ON pay2.date_begin > pay1.date_end
GROUP BY pay1.date_begin
ORDER BY pay1.date_begin ASC
But the result is
pay1.date_begin date_end pay2.date_begin date_end difference
2010-08-01 2010-08-15 2010-08-31 2010-09-12 16 wrong
2010-08-16 2010-08-30 2010-08-31 2010-09-12 1 correct
2010-08-31 2010-09-12 2010-10-01 2010-10-15 19 correct
2010-10-01 2010-10-15 NULL NULL
If I delete the GROUP BY I can see that there are correct rows in the result. I just can't figure out how to get them.
Is there a way to sort table before being joined?