Dynamically creating date periods using MySQL

前端 未结 2 1320
说谎
说谎 2020-12-11 04:15

I trying to get the Grape count from dates March 1 - 3.

\"enter

You will notic

2条回答
  •  猫巷女王i
    2020-12-11 05:09

    Remember there is a dynamically (and a bit ugly) solution to creating a date range that does not require creating a table:

    select aDate from (
      select @maxDate - interval (a.a+(10*b.a)+(100*c.a)+(1000*d.a)) day aDate from
      (select 0 as a 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) a, /*10 day range*/
      (select 0 as a 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) b, /*100 day range*/
      (select 0 as a 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) c, /*1000 day range*/
      (select 0 as a 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) d, /*10000 day range*/
      (select @minDate := '2001-01-01', @maxDate := '2002-02-02') e
    ) f
    where aDate between @minDate and @maxDate
    

    Depending on the length of the date range you can reduce the amount of dynamically generated results (10000 days means over 27 years of records each representing one day) by removing tables (d, c, b and a) and removing them from the upper formula. Setting the @minDate and @maxDate variables will allow you to specify the dates between you want to filter the results.

    Edit:

    I see you're still looking for a solution. Try this:

    select c.date, f.fruitName, count(f.fruitName = 'Grapes')
    from tbl_calendar c
    left join tbl_fruits f
    on c.date = f.fruitDate and f.fruitName = 'Grapes'
    group by c.date, f.fruitName
    

    If you also want to filter the extra dates from the created table, use this query:

    select c.date, f.fruitName, count(f.fruitName = 'Grapes')
    from tbl_calendar c
    left join tbl_fruits f
    on c.date = f.fruitDate and f.fruitName = 'Grapes'
    group by c.date, f.fruitName
    having c.date between
      (select min(fruitDate) from tbl_fruits) and
      (select max(fruitDate) from tbl_fruits)
    

提交回复
热议问题