August 10, 2010
Sql unique distinct select
Problem
Write code to simulate the SQL statement “Select unique emp_name from employees”
Solution
Assuming we have an array of employee names we need to write a function that prints the unique employee names in the array. We can use a built in hash table for that matter. Just hash all names then print the keys in the hash table. That is all what we need to do.
Code
Here is how to do that in perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# Array of names @Names = ("Sam", "Joe", "Sam", "Mohammed", "Sam", "Mohammed"); # Hash data structure %H = (); # Add the names to the hash table foreach $name (@Names) { # name is used as the key # and the value is the count # of that name in the array # note that we are not interested # in the count itself. Duplicate # names hash to the same spot # so going through the hash will # give us the unique names $H{$name}++; } # Print the Hash you get all unique names foreach $name (keys %H) { print "Name = " . $name . " : Count = " . $H{$name} . "\\n"; } |
Please use the comments section below for feedback. Thanks for reading.