如何从SQL中的列中选择不同数量的值?

时间:2014-11-16 18:18:23

标签: sql sql-server database count distinct

数据库包含REGISTRATION表和STUDENT表。

REGISTRATION表的列是:

CourseID, StudentID, CourseCode, Score, Year

CourseCode列包含CS-101MS-202等课程代码(每个学生ID都注册到许多课程)。我需要找到学生参加3门以上课程的名字和身份证。

我试过了:

Select distinct 
    CourseRegistrations.S_ID, Students.FirstName
from 
    Students, CourseRegistrations
where 
    Students.StudentID = CourseRegistrations.StudentID 
group by
    CourseRegistrations.S_ID, Students.FirstName 
having 
    count(distinct CourseRegistrations.CourseCode) > 3

但这显示了文件的所有记录。

2 个答案:

答案 0 :(得分:0)

如果您使用Distinct

,则不需要

GROUP BY

Select CusReg.S_ID
from Students stud join CourseRegistrations CusReg
ON stud.StudentID=CusReg.StudentID 
GROUP BY CourseRegistrations.S_ID 
having count(CusReg.CourseCode)>3

不要使用旧样式联接

SOURCE

答案 1 :(得分:0)

你应该尝试:

Select CourseRegistrations.StudentID, count(CourseRegistrations.CourseCode)
from Students, CourseRegistrations
where Students.StudentID=CourseRegistrations.StudentID 
GROUP BY CourseRegistrations.StudentID
having count(CourseRegistrations.CourseCode)>3