带内分组的双内连接

时间:2013-09-05 07:58:56

标签: sql

这是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的年份= $年部分来解决,因为这将使我所有学生都在该机构注册。我只想从目前注册的学生那里了解这群学生注册了多少次。

我认为多次使用JOIN语句应该有所帮助(即在同一个表中包含另一个连接uctProgrammesRegistered,但不知何故仅使用WHERE programmeregistered ='“。$ programmeCode。”'并且不进行年度检查 - 这将起作用,但SQL似乎没有配合这个想法。

1 个答案:

答案 0 :(得分: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