What is the most straightforward way to pad empty dates in sql results (on either mysql or perl end)?

后端 未结 9 1895
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 06:12

I\'m building a quick csv from a mysql table with a query like:

select DATE(date),count(date) from table group by DATE(date) order by date asc;
9条回答
  •  感动是毒
    2020-11-22 06:53

    When you need something like that on server side, you usually create a table which contains all possible dates between two points in time, and then left join this table with query results. Something like this:

    create procedure sp1(d1 date, d2 date)
      declare d datetime;
    
      create temporary table foo (d date not null);
    
      set d = d1
      while d <= d2 do
        insert into foo (d) values (d)
        set d = date_add(d, interval 1 day)
      end while
    
      select foo.d, count(date)
      from foo left join table on foo.d = table.date
      group by foo.d order by foo.d asc;
    
      drop temporary table foo;
    end procedure
    

    In this particular case it would be better to put a little check on the client side, if current date is not previos+1, put some addition strings.

提交回复
热议问题