Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: Counting events and getting top 5 matches

by jonadab (Parson)
on Sep 17, 2008 at 11:14 UTC ( #711961=note: print w/ replies, xml ) Need Help??

in reply to Counting events and getting top 5 matches

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.

We're working on a six-year set of freely redistributable Vacation Bible School materials.

Comment on Re: Counting events and getting top 5 matches
Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://711961]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2014-09-18 21:52 GMT
Find Nodes?
    Voting Booth?

    How do you remember the number of days in each month?

    Results (124 votes), past polls