generate days from date range

后端 未结 29 3155
渐次进展
渐次进展 2020-11-21 05:19

I would like to run a query like

select ... as days where `date` is between \'2010-01-20\' and \'2010-01-24\'

And return data like:

29条回答
  •  暖寄归人
    2020-11-21 06:16

    The old school solution for doing this without a loop/cursor is to create a NUMBERS table, which has a single Integer column with values starting at 1.

    CREATE TABLE  `example`.`numbers` (
      `id` int(10) unsigned NOT NULL auto_increment,
      PRIMARY KEY  (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

    You need to populate the table with enough records to cover your needs:

    INSERT INTO NUMBERS (id) VALUES (NULL);
    

    Once you have the NUMBERS table, you can use:

    SELECT x.start_date + INTERVAL n.id-1 DAY
      FROM NUMBERS n
      JOIN (SELECT STR_TO_DATE('2010-01-20', '%Y-%m-%d') AS start_date 
              FROM DUAL) x
     WHERE x.start_date + INTERVAL n.id-1 DAY <= '2010-01-24'
    

    The absolute low-tech solution would be:

    SELECT STR_TO_DATE('2010-01-20', '%Y-%m-%d')
     FROM DUAL
    UNION ALL
    SELECT STR_TO_DATE('2010-01-21', '%Y-%m-%d')
     FROM DUAL
    UNION ALL
    SELECT STR_TO_DATE('2010-01-22', '%Y-%m-%d')
     FROM DUAL
    UNION ALL
    SELECT STR_TO_DATE('2010-01-23', '%Y-%m-%d')
     FROM DUAL
    UNION ALL
    SELECT STR_TO_DATE('2010-01-24', '%Y-%m-%d')
     FROM DUAL
    

    What would you use it for?


    To generate lists of dates or numbers in order to LEFT JOIN on to. You would to this in order to see where there are gaps in the data, because you are LEFT JOINing onto a list of sequencial data - null values will make it obvious where gaps exist.

提交回复
热议问题