1

这是 SQL 爱好者的一个:

我有两个表:学生姓名和学生注册。学生一年内注册 1 到 2 次,在学位课程中注册 8 到 10 次。我想提取系统中当前的所有学生(即 2013 年的所有学生),我使用以下方法:

SELECT studentkey, lastname, firstname, COUNT(year) AS registrations
    FROM  uctProgrammesRegistered 
    LEFT JOIN uctStudents
    ON uctStudents.studentnumber=uctProgrammesRegistered.studentkey
    WHERE programmeregistered='".$programmeCode."' AND year='".$year."' 
    GROUP BY studentkey, lastname, firstname
    ORDER BY studentkey, lastname

这给了我当年注册次数的结果。但是,我真正想要的是学生在过去几年中注册的次数。请注意,这不能通过放宽 WHERE 的 year=$year 部分来解决,因为这会给我所有在该机构注册过的学生。我只是想从目前注册的学生那里知道这组学生注册了多少次。

我认为多次使用 JOIN 语句应该会有所帮助(即在同一个表 uctProgrammesRegistered 上包含另一个联接,但不知何故只有 WHERE programregistered='".$programmeCode."' 并省略了年份检查 - 这会起作用,但 SQL 不会似乎不配合这个想法。

4

1 回答 1

1

尝试这个:

Select studentkey, lastname, firstname, 
     Count(*) registrations
From  uctStudents s
   Join uctProgrammesRegistered  r 
       on r.studentkey = s.studentnumber
Where Exists(Select * from uctProgrammesRegistered 
             Where studentkey = s.studentnumber
                 And year='".$year."')
Group By studentkey, lastname, firstname
Order By studentkey, lastname

或者 ...

Select studentkey, lastname, firstname, 
     Sum(Case when year = 2013 then 1 else 0 end) Registrations2013,
     Count(*) TotalRegistrations
From  uctStudents s
   Join uctProgrammesRegistered  r 
       on r.studentkey = s.studentnumber
Where Exists(Select * from uctProgrammesRegistered 
             Where studentkey = s.studentnumber
                 And year='".$year."')
Group By studentkey, lastname, firstname
Order By studentkey, lastname
于 2013-09-05T08:03:42.157 回答