多个Group by子句

时间:2018-02-08 19:44:10

标签: grouping

我需要根据class_code和course_code计算学生人数,同时根据课程计算学生人数。我需要两个结果。

这是我的代码

SELECT 
 Class_code,Course_code, Count(OEN)
FROM section52D    
GROUP BY Class_code, Course_code

它解决了第一部分,但我仍然需要根据course_code进行计数。

2 个答案:

答案 0 :(得分:1)

假设您使用的是Sql Server 2008,我希望这可以帮助您:

SELECT Class_code,Course_code, Count(OEN) as count_basedOn_classAndCourse
into #temp
FROM section52D
GROUP BY Class_code, Course_code

SELECT Course_code, Count(OEN) as count_basedOn_Course
into #temp2
FROM section52D
GROUP BY Course_code

select * from #temp1
select * from #temp2

select t1.Course_Code , t1.Class_Code, 
       t1.count_basedOn_classAndCourse, 
       t2.count_basedOn_Course
from #temp1 t1
left outer join #temp2 t2 on t1.Course_Code = t2.Course_Code 

答案 1 :(得分:0)

您可以尝试:

SELECT Class_code,
       Course_code,
       (select Count(OEN) FROM section52D) as totalOEN 
from section52D
GROUP BY Class_code, Course_code