简体   繁体   中英

How to count occurrences of a column value in SQL?

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?

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.

要计算相同年龄的学生:

select age ,count(age) from s_table group by age 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM