Tuesday, October 16, 2012

SQL Query to find out the frequency of each element in a column

Suppose we have a table "Person" as:

IdLastNameFirstNameAgeCity
1SmithJohn33Newyork
2SmithMike34Boston
3PaulRyan39Chicago
4WilliamBrian45Baltimore
5RaoSunita41Dayton
6ZingSue33Owings Mills
7SmithRobert45Newyork
8PaulZean33Chicago
9SrivastavaHemant33Baltimore
10RaoVenkat45Dayton


and we need to find out the frequency of the each age.


   SELECT Age, COUNT(Age)AS Frequency    
   FROM Persons   
   GROUP BY Age   
   ORDER BY    
   COUNT(Age) DESC
 

We get following result:
Age
Frequency
33
4
45
3
34
1
39
1


Now suppose we want to get the ‘Age’ which occurs more than equal to 2. For this query, we need to add HAVING clause after GROUP BY clause.



SELECT Age, COUNT(Age)AS Frequency
FROM Persons
GROUP BY Age 
HAVING  COUNT(Age) >= 2

That gives result as:
Age
Frequency
33
4
45
3


No comments:

Post a Comment