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

后端 未结 9 1892
伪装坚强ぢ
伪装坚强ぢ 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 07:09

    You could use a DateTime object:

    use DateTime;
    my $dt;
    
    while ( my ($date, $sum) = $sth->fetchrow )  {
        if (defined $dt) {
            print CSV $dt->ymd . ",0\n" while $dt->add(days => 1)->ymd lt $date;
        }
        else {
            my ($y, $m, $d) = split /-/, $date;
            $dt = DateTime->new(year => $y, month => $m, day => $d);
        }
        print CSV, "$date,$sum\n";
    }
    

    What the above code does is it keeps the last printed date stored in a DateTime object $dt, and when the current date is more than one day in the future, it increments $dt by one day (and prints it a line to CSV) until it is the same as the current date.

    This way you don't need extra tables, and don't need to fetch all your rows in advance.

提交回复
热议问题