日期在季节之间传播

时间:2013-06-12 12:58:05

标签: mysql sql period

在我的MySQL数据库表中,我有以下日期(季节):

sstart,send,sname
2013-05-01,2013-05-31,'season1'
2013-06-01,2013-06-30,'season2'

我想创建SQL查询,该查询将针对给定的开始日期和结束日期在季节之间分割这段时间,并提供有关每个时期的持续时间的信息:

例如,对于以下期间(qstart,qend),2013-04-20,2013-06-10此查询应返回:

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

我有以下SQL查询:

SELECT sid,sname,DATEDIFF(IF(send>@qend,@qend,send),IF(sstart<@qstart,@qstart,sstart))+1
               FROM seasons WHERE sstart<=@qend AND send>=@qstart

我的问题是当我的句号(qstart,qend)在第一季开始或在数据库的最后一个季节之后结束时,此查询不会返回我需要的这些尾部。

2 个答案:

答案 0 :(得分:0)

我没有mySQL,但这应该指向正确的方向:

使用以下内容代替查询中的Seasons表:

   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         

基本上,添加两个“虚拟行”来表示第一个日期之前和最后一个日期之后的季节...

答案 1 :(得分:0)

对于其他人,根据Sparky的建议,这里是我的查询:

SELECT sid,sstart,send,sname,DATEDIFF(IF(send>@lDay,@lDay,send),IF(sstart<@fDay,@fDay,sstart))+1 AS duration
FROM
(
  SELECT 0 AS sid,'undefined' AS sname,'1980-01-01' AS sstart,SUBDATE(MIN(sstart),1) AS send FROM seasons
    UNION
  SELECT sid,sname,sstart,send FROM seasons
    UNION
  SELECT 0 AS sid,'undefined' AS sname,ADDDATE(MAX(send),1) AS sstart,'2021-12-31' AS send FROM seasons
) AS seasons
WHERE sstart<=@lDay AND send>=@fDay
ORDER BY sstart