my %hUsers; #find all unique combinations of user and product while(my @row = $res->fetchrow_array()) { my ($username, $product) = @row; $hUsers->{$username}{$product} = 1; } # print product counts per user foreach $user_name (sort keys %$hUsers) { print $user_name, ' ', scalar keys $hUsers{$user_name}, "\n"; }