generate days from date range

后端 未结 29 2480
渐次进展
渐次进展 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:02

    Can create a procedure also to create calendar table with timestmap different from day. If you want a table for each quarter

    e.g.

    2019-01-22 08:45:00
    2019-01-22 09:00:00
    2019-01-22 09:15:00
    2019-01-22 09:30:00
    2019-01-22 09:45:00
    2019-01-22 10:00:00
    

    you can use

    CREATE DEFINER=`root`@`localhost` PROCEDURE `generate_calendar_table`()
    BEGIN
    
    select unix_timestamp('2014-01-01 00:00:00') into @startts;
    select unix_timestamp('2025-01-01 00:00:00') into @endts;
    
    if ( @startts < @endts ) then
    
        DROP TEMPORARY TABLE IF EXISTS calendar_table_tmp;
    
        CREATE TEMPORARY TABLE calendar_table_tmp (ts int, dt datetime); 
    
        WHILE ( @startts < @endts)
            DO 
            SET @startts = @startts + 900;
            INSERT calendar_table_tmp VALUES (@startts, from_unixtime(@startts));
        END WHILE;
    
    END if;
    
    END
    
    
    

    and then manipulate through

    select ts, dt from calendar_table_tmp;
    
    

    that give you also ts

    '1548143100', '2019-01-22 08:45:00'
    '1548144000', '2019-01-22 09:00:00'
    '1548144900', '2019-01-22 09:15:00'
    '1548145800', '2019-01-22 09:30:00'
    '1548146700', '2019-01-22 09:45:00'
    '1548147600', '2019-01-22 10:00:00'
    

    from here you can start to add other information such as

    select ts, dt, weekday(dt) as wd from calendar_table_tmp;
    
    

    or create a real table with create table statement

提交回复
热议问题