I need to do two things: 1) get the number of occurrences of each code 2) get the top 5 username/userid pair for each of these code
My SQL isn't up to that sort of processing (I mostly just use SQL for data _retrieval_), so I'm going to go for a Perl answer. I assume you are using DBI and already have a connection to the database in question; I'm going to call the DBI connection $db for lack of a better name.
my $query = $db->prepare("select code, username, userid from transac +tions"); $query->execute(); my %code = map { $_ => [] } 0 .. 13; while (my $r = $qeury->fetchrow_hashref()) { my $c = $$r{code}; push @{$code{$c}}, $r; } # For each code $c, $code{$c} is now an arrayref which # contains the relevant records (as hashrefs). The # number of elements in the array equals the number # of occurances. Now, for the second part... my %topfive; for my $c (keys %code) { my %user; for my $row (@{$code{$c}}) { # Note: this assumes that the userid field # is unique to each user. $user{$$row{userid}}{count}++; $user{$$row{userid}}{name} = $$row{username}; } $topfive{$c} = [(sort { $$b[2] <=> $$a[2] } map { [$_, $user{$_}{name}, $user{$_}{count}] } keys %user)[0 .. 4]]; }
If you have trouble understanding how any of this code works, just ask about the part you have trouble with, and someone will explain it.
This feels like a business problem to me, but on the off chance that it is actually homework, note that your professor will certainly be able to tell you didn't write the above code if you just copy it verbatim. It contains several Perl idioms that a beginning student would not have written.
In reply to Re: Counting events and getting top 5 matches
by jonadab
in thread Counting events and getting top 5 matches
by iphony
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |