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

后端 未结 9 1835
伪装坚强ぢ
伪装坚强ぢ 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:58

    Since you don't know where the gaps are, and yet you want all the values (presumably) from the first date in your list to the last one, do something like:

    use DateTime;
    use DateTime::Format::Strptime;
    my @row = $sth->fetchrow;
    my $countdate = strptime("%Y-%m-%d", $firstrow[0]);
    my $thisdate = strptime("%Y-%m-%d", $firstrow[0]);
    
    while ($countdate) {
      # keep looping countdate until it hits the next db row date
      if(DateTime->compare($countdate, $thisdate) == -1) {
        # counter not reached next date yet
        print CSV $countdate->ymd . ",0\n";
        $countdate = $countdate->add( days => 1 );
        $next;
      }
    
      # countdate is equal to next row's date, so print that instead
      print CSV $thisdate->ymd . ",$row[1]\n";
    
      # increase both
      @row = $sth->fetchrow;
      $thisdate = strptime("%Y-%m-%d", $firstrow[0]);
      $countdate = $countdate->add( days => 1 );
    }
    

    Hmm, that turned out to be more complicated than I thought it would be.. I hope it makes sense!

提交回复
热议问题