How to count occurrences of a column value efficiently in SQL?
This should work:
SELECT age, count(age)
FROM Students
GROUP by age
If you need the id as well you could include the above as a sub query like so:
SELECT S.id, S.age, C.cnt
FROM Students S
INNER JOIN (SELECT age, count(age) as cnt
FROM Students
GROUP BY age) C ON S.age = C.age
If you're using Oracle, then a feature called analytics will do the trick. It looks like this:
select id, age, count(*) over (partition by age) from students;
If you aren't using Oracle, then you'll need to join back to the counts:
select a.id, a.age, b.age_count
from students a
join (select age, count(*) as age_count
from students
group by age) b
on a.age = b.age
Here's another solution. this one uses very simple syntax. The first example of the accepted solution did not work on older versions of Microsoft SQL (i.e 2000)
SELECT age, count(*)
FROM Students
GROUP by age
ORDER BY age