Search code examples
sqlsql-serversql-server-2000

Get column value used in most rows - SQL


Let say I have a table for each egg layed with details like,

EggTable
 - Egg Identitfier (Name + Number)
 - Chicken Name Which Layed Egg
 - Time of Egg Came out

Now I want to know which Chicken layed most eggs, I am not really sure which SQL function or query can I use.

Please note, I don't want to specify any parameter. and need chicken name as output, thank you.


Solution

  • SELECT COUNT(*) AS NumOfEggs, ChickenName
    FROM Eggs
    GROUP BY ChickenName
    

    This groups the entries in the table by the chicken name and sums up how many entries there are per chicken name.

    You can now select the entry with the most eggs like this:

    SELECT TOP 1 NumOfEggs, ChickenName FROM
    (
        SELECT COUNT(*) AS NumOfEggs, ChickenName
        FROM Eggs
        GROUP BY ChickenName
    )
    ORDER BY NumOfEggs DESC