如何计算SQL中列值的出现次数?

时间:2014-08-28 08:40:10

标签: sql sql-server-2008

我有一张学生表:

id | age|num
-------------
0  | 25| 10
1  | 25| 5
2  | 23| 5

我想查询所有学生,还有一个额外的专栏可以计算同一年龄段的学生数量:

id | num | age | agecount|numcount
-------------------------------------
0  | 10 | 25  | 2       |1
1  | 5  | 23  | 1       |2

最有效的方法是什么?如果有更好的方法**。有吗?

2 个答案:

答案 0 :(得分:2)

您有两个问题:

一个学生名单:

SELECT
    id, age, num
FROM
   students

还有一个年龄相同的学生:

SELECT
   age
   , count(1)
FROM
   students
GROUP BY
   age

现在你必须结合这两个查询: 您可以加入一个或多个表或子查询。让我们这样做:

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

您可以通过删除第一个子查询来简化上述查询,并改为使用学生表:

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

现在您可以修改此示例查询以实现目标。

答案 1 :(得分:0)

计算年龄相同的学生:

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