我有如下的sql:
select a.dept, a.name
from students a
group by dept, name
order by dept, name
得到结果:
dept name
-----+---------
CS | Aarthi
CS | Hansan
EE | S.F
EE | Nikke2
我想总结一下每个部门的学生人数如下:
dept name count
-----+-----------+------
CS | Aarthi | 2
CS | Hansan | 2
EE | S.F | 2
EE | Nikke2 | 2
Math | Joel | 1
我该怎么写sql?
答案 0 :(得分:18)
虽然看起来你没有显示所有表格,但我只能假设每个学生还有另一张实际入学表格
select a.Dept, count(*) as TotalStudents
from students a
group by a.Dept
如果你想要与每个学生相关的每个部门的总数(没有意义),你可能必须这样做......
select a.Dept, a.Name, b.TotalStudents
from students a,
( select Dept, count(*) TotalStudents
from students
group by Dept ) b
where a.Dept = b.Dept
我对你的“姓名”栏目的解释是学生的名字而不是班级的实际讲师,因此我的子选择/加入。否则,就像其他人一样,只需使用COUNT(*)作为第三列即可。
答案 1 :(得分:6)
select a.dept, a.name,
(SELECT count(*)
FROM students
WHERE dept = a.dept)
from students a
group by dept, name
order by dept, name
这是一个有点可疑的查询,因为您获得了部门计数的重复副本。获取学生列表更加清晰,部门计算为单独的结果。当然,出于另一种方式可能有实际的理由,所以这不是一个绝对的规则。
答案 2 :(得分:1)
SELECT dept, name, COUNT(name) as CT from students
group by dept, name
order by dept, name
答案 3 :(得分:0)
这应该这样做(我没有任何环境可以在最短时间内进行测试)
select a.dept, a.name, count(a.*) as NumOfStudents
from students a
group by dept, name order by dept, name
HTH
答案 4 :(得分:0)
或者简单地写一下
select dept, name, count(name) as nostud from students group by dept, name order by dept, name
答案 5 :(得分:0)
这将给出上面要求的结果
select a.dept, a.name, cnt
from student a
join (
select dept, count(1) as cnt
from student
group by dept
) b on b.dept = a.dept