Get a list of dates between two dates

后端 未结 20 2455
醉梦人生
醉梦人生 2020-11-22 00:26

Using standard mysql functions is there a way to write a query that will return a list of days between two dates.

eg given 2009-01-01 and 2009-01-13 it would return

20条回答
  •  情歌与酒
    2020-11-22 01:04

    I needed a list with all months between 2 dates for statistics. The 2 dates are the start and enddate from a subscription. So the list shows all months and the amount of subscriptions per month.

    MYSQL

    CREATE PROCEDURE `get_amount_subscription_per_month`()
    BEGIN
       -- Select the ultimate start and enddate from subscribers
       select @startdate := min(DATE_FORMAT(a.startdate, "%Y-%m-01")), 
              @enddate := max(DATE_FORMAT(a.enddate, "%Y-%m-01")) + interval 1 MONTH
       from subscription a;
    
       -- Tmp table with all months (dates), you can always format them with DATE_FORMAT) 
       DROP TABLE IF EXISTS tmp_months;
       create temporary table tmp_months (
          year_month date,
          PRIMARY KEY (year_month)
       );
    
    
       set @tempDate=@startdate;  #- interval 1 MONTH;
    
       -- Insert every month in tmp table
       WHILE @tempDate <= @enddate DO
         insert into tmp_months (year_month) values (@tempDate);
         set @tempDate = (date(@tempDate) + interval 1 MONTH);
       END WHILE;
    
       -- All months
       select year_month from tmp_months;
    
       -- If you want the amount of subscription per month else leave it out
       select mnd.year_month, sum(subscription.amount) as subscription_amount
       from tmp_months mnd
       LEFT JOIN subscription ON mnd.year_month >= DATE_FORMAT(subscription.startdate, "%Y-%m-01") and mnd.year_month <= DATE_FORMAT(subscription.enddate, "%Y-%m-01")
       GROUP BY mnd.year_month;
    
     END
    

提交回复
热议问题