在子查询中使用group by子句和count()

时间:2015-08-06 16:01:02

标签: sql sql-server database

表:类

class_id    ClassName
----------------------
1           AAA
2           BBB
3           CCC

表:组

id    class_id   GroupName
---------------------------
1      1          A1
2      1          A2
3      2          B1
4      3          C1
5      2          B2
6      1          A3

预期产出:

class_id   ClassName  count(*)
-------------------------------
1          AAA         3
2          BBB         2
3          CCC         1

1 个答案:

答案 0 :(得分:0)

使用内部联接获得结果:

SELECT        Class.class_id, Class.ClassName, COUNT(*) AS count
FROM            Class INNER JOIN
                         Groups ON Class.class_id = Groups.class_id
GROUP BY Class.class_id, Class.ClassName