【问题标题】:How can I select distinct number of values from a column in SQL?如何从 SQL 中的列中选择不同数量的值?
【发布时间】:2014-11-16 18:18:23
【问题描述】:

数据库包含REGISTRATION 表和STUDENT 表。

REGISTRATION 表的列是:

CourseID, StudentID, CourseCode, Score, Year

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

我试过了:

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

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

【问题讨论】:

标签: sql sql-server database count distinct


【解决方案1】:

你应该试试:

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

【讨论】:

    【解决方案2】:

    如果您使用GROUP BY,则不需要Distinct

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多