Ranking records with how many times they exist

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sukatoa
    Contributor
    • Nov 2007
    • 539

    #1

    Ranking records with how many times they exist

    For example:

    Cat
    Dog
    Cow
    Rat
    Cat
    Cat
    Rat
    Cow
    Cow
    Cow

    (RESULT)
    Where it exist:
    Cow 4 times
    Cat 3 times
    Rat 2 times
    Dog 1 time

    I would like to have a result like the one i mentioned above (RESULT)

    How would it be queried like?

    The current implementation has 2 queries, 1st is to select them distinctly, 2nd is one by one, each of the unique result will select again the db to count how many times it exist, i think it is a bad implementation and i hope it is possible to query once in the DB Server, any ideas?
  • mwasif
    Recognized Expert Contributor
    • Jul 2006
    • 802

    #2
    This can be achieved by COUNT() and GROUP BY.

    [code=mysql]SELECT column_name, COUNT(*) as occurence FROM table_name
    GROUP BY column_name
    ORDER BY occurence DESC[/code]

    Comment

    • nbiswas
      New Member
      • May 2009
      • 149

      #3
      Solution to Ranking records with how many times they exist

      Try this

      Code:
      select Result = animals + '  ' +  CAST(COUNT(animals) as varchar(10))  + '  times'
      from AnimalTable
      group by animals 
      order by COUNT(animals) desc
      Output:
      Code:
      Result
      Cow  4  times
      Cat  3  times
      Rat  2  times
      Dog  1  times

      Comment

      • sukatoa
        Contributor
        • Nov 2007
        • 539

        #4
        Thank you for your replies experts. Effective =)

        Comment

        Working...