Reputation: 777
I have a table of students:
id | age|num
-------------
0 | 25| 10
1 | 25| 5
2 | 23| 5
I want to query for all students, and an additional column that counts how many students are of the same age:
id | num | age | agecount|numcount
-------------------------------------
0 | 10 | 25 | 2 |1
1 | 5 | 23 | 1 |2
What's the most efficient way of doing this? if there's a better way**. Is there?
Upvotes: 1
Views: 4939
Reputation: 9042
You have two queries:
One for the list of the students:
SELECT
id, age, num
FROM
students
And one for the count of students with the same age:
SELECT
age
, count(1)
FROM
students
GROUP BY
age
Now you have to combine these two queries: You can JOIN one or more tables or subqueries. Lets do it:
SELECT
S.id, S.age, S.num, age.cnt
FROM
-- List of all students
(
SELECT
id, age, num
FROM
students
) S
-- Ages with student counts
INNER JOIN (
SELECT
age
, count(1) AS cnt
FROM
students
GROUP BY
age
) A
ON S.age = A.age
You can simplify the above query with removing the first subquery and use the students table instead:
SELECT
S.id, S.age, S.num, A.cnt
FROM
students S
-- Ages with student counts
INNER JOIN (
SELECT
age
, count(1) AS cnt
FROM
students
GROUP BY
age
) A
ON students.age = age.age
Now you can modify this sample query to achieve your goal.
Upvotes: 2
Reputation: 857
To count student with the same age :
select age ,count(age) from s_table group by age
Upvotes: 0