MySQL how to fill missing dates in range?

前端 未结 5 600
离开以前
离开以前 2020-11-21 06:47

I have a table with 2 columns, date and score. It has at most 30 entries, for each of the last 30 days one.

date      score
-----------------
1.8.2010  19
2         


        
5条回答
  •  被撕碎了的回忆
    2020-11-21 07:11

    Time went by since this question was asked. MySQL 8.0 was released in 2018 and added support for recursive common table expressions, which provide an elegant, state-of-the-art way to solve this question.

    The following query can be used to generate a list of dates, say for the first 15 days of August 2010:

    with recursive all_dates(dt) as (
        -- anchor
        select '2010-08-01' dt
            union all 
        -- recursion with stop condition
        select dt + interval 1 day from all_dates where dt + interval 1 day <= '2010-08-15'
    )
    select * from all_dates
    

    You can then left join this resultset with your table to generate the expected output:

    with recursive all_dates(dt) as (
        -- anchor
        select '2010-08-01' dt
            union all 
        -- recursion with stop condition
        select dt + interval 1 day from all_dates where dt + interval 1 day <= '2010-08-15'
    )
    select d.dt date, coalesce(t.score, 0) score
    from all_dates d
    left join mytable t on t.date = d.dt
    order by d.dt
    

    Demo on DB Fiddle:

    date       | score
    :--------- | ----:
    2010-08-01 |    19
    2010-08-02 |    21
    2010-08-03 |     0
    2010-08-04 |    14
    2010-08-05 |     0
    2010-08-06 |     0
    2010-08-07 |    10
    2010-08-08 |     0
    2010-08-09 |     0
    2010-08-10 |    14
    2010-08-11 |     0
    2010-08-12 |     0
    2010-08-13 |     0
    2010-08-14 |     0
    2010-08-15 |     0
    

提交回复
热议问题