my %sections; while (my $row = $sth->fetchrow_arrayref) { my ($section, $year, $month, $value) = @$row{qw/ Bereich Jahr Monat Wert /}; $sections{$section}->{$year}->{$month} = $value; } for my $section (sort keys %sections) { print "$section |"; my $years = $sections{$section}; for my $year (sort keys %$years) { print " $year|"; my $months = $years->{$year}; my @values = map { defined $months->{$_} ? $months->{$_} : "" } 1 .. 12; local $" = " | "; say "@values"; } }