0

在我的 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)在第一季之前开始或在数据库中的最后一季之后结束时,此查询不会返回我需要的这些尾巴。

4

2 回答 2

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
于 2013-06-12T14:38:42.560 回答
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         

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

于 2013-06-12T13:53:37.863 回答