generate days from date range

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

    Here is another variation using views:

    CREATE VIEW digits AS
      SELECT 0 AS digit UNION ALL
      SELECT 1 UNION ALL
      SELECT 2 UNION ALL
      SELECT 3 UNION ALL
      SELECT 4 UNION ALL
      SELECT 5 UNION ALL
      SELECT 6 UNION ALL
      SELECT 7 UNION ALL
      SELECT 8 UNION ALL
      SELECT 9;
    
    CREATE VIEW numbers AS
      SELECT
        ones.digit + tens.digit * 10 + hundreds.digit * 100 + thousands.digit * 1000 AS number
      FROM
        digits as ones,
        digits as tens,
        digits as hundreds,
        digits as thousands;
    
    CREATE VIEW dates AS
      SELECT
        SUBDATE(CURRENT_DATE(), number) AS date
      FROM
        numbers;
    

    And then you can simply do (see how elegant it is?):

    SELECT
      date
    FROM
      dates
    WHERE
      date BETWEEN '2010-01-20' AND '2010-01-24'
    ORDER BY
      date
    

    Update

    It is worth noting that you will only be able to generate past dates starting from the current date. If you want to generate any kind of dates range (past, future, and in between), you will have to use this view instead:

    CREATE VIEW dates AS
      SELECT
        SUBDATE(CURRENT_DATE(), number) AS date
      FROM
        numbers
      UNION ALL
      SELECT
        ADDDATE(CURRENT_DATE(), number + 1) AS date
      FROM
        numbers;
    

提交回复
热议问题