【问题标题】:MySQL: Expand date range into new rowsMySQL:将日期范围扩展到新行
【发布时间】:2012-03-15 17:52:41
【问题描述】:

我在 MySQL 中有一个表,其中包含每个键的最小和最大日期值:

key |   minDate   |   maxDate
 1     2011-01-01   2011-01-10 
 2     2011-02-13   2011-02-15
 3     2011-10-19   2011-12-10

如何为每个键的 minDate 和 maxDate 之间的每个日期创建一个包含一行的新表:

key |     Date   
 1     2011-01-01
 1     2011-01-02
 ...     ...
 1     2011-01-10
 2     2011-02-13
 2     2011-02-14
 2     2011-02-15
 3     2011-10-19
 ...     ...

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    使用integers table,您可以这样做:

        SELECT "key", minDate + INTERVAL i DAY
          FROM mytable
    INNER JOIN integers
               ON i <= DATEDIFF(maxDate, minDate)
    

    当然,假设“整数”表的列名为“i”。

    您可以从那里使用INSERT INTO ... SELECT 填充新表。

    【讨论】:

    • 您还可以动态生成整数SELECT t1 + t2 * 10 AS i FROM (select 0 t1 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1, (select 0 t2 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2
    【解决方案2】:

    使用递归公用表表达式(需要 mysql 8 或 mariadb 10.2+):

    with recursive expanded_ranges as (
        select id, mindate dt
        from ranges
        union all
        select expanded_ranges.id, expanded_ranges.dt+interval 1 day
        from expanded_ranges
        join ranges on expanded_ranges.id=ranges.id and dt<maxdate
    )
    select * From expanded_ranges;
    

    fiddle

    【讨论】:

      【解决方案3】:

      根据记忆,可能是这样的:

      create table #res (
      key int,
      Date datetime
      )
      
      declare @minD datetime, @maxD datetime
      select @minD = min(minDate), @maxD = max(maxDate) from tablename
      
      while @minD <= @maxD do
         insert into #res
         select key, @minD from tablename where @minD >= minDate and @minD <= maxDate
      
         select @minD = dateadd(@minD, interval 1 day)
      end while;
      
      select key, Date from #res
      
      drop table #res
      

      【讨论】:

      • 不知道这是什么,但不是mysql
      猜你喜欢
      • 2018-07-30
      • 2020-05-19
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多