In my MySQL database table I have the following date periods (seasons):
sstart,send,sname
2013-05-01,2013-05-31,'season1'
2013-06-01,2013-06-30,'season2'
I'd like to create SQL query which will for given start and end date split this period among seasons with info about duration of each part of period:
For example for the following period (qstart,qend) 2013-04-20,2013-06-10 this query should return:
2013-04-20,2013-04-30,'',11 <-- this is important - I need it
2013-05-01,2013-05-31,'season1',31 <-- 31 days of my period is in season1
2013-06-01,2013-06-10,'season2',10 <-- 10 days of my period is in season2
I have the following SQL query:
SELECT sid,sname,DATEDIFF(IF(send>@qend,@qend,send),IF(sstart<@qstart,@qstart,sstart))+1
FROM seasons WHERE sstart<=@qend AND send>=@qstart
My problem is when my period (qstart,qend) starts before first season or ends after the last season in database, this query does not return these tails which I need.
I don't have mySQL, but this should hopefully point you in the right direction:
Instead of the Seasons table in your query, using the following:
FROM
(
select * from seasons
union
select '' as [sname],'1/1/1980' as [sStart],DateAdd(dd,-1,MIN([sStart])) as [send]
from Seasons
union
select '' as [sname],DateAdd(dd,+1,MAX([send])) as [sstart],'12/31/2021' as [Send]
from Seasons
) Seasons
Basically, adding two "dummy rows" to represent seasons before the first date and after the last date...