SQL语句相同列不同的数据

时间:2010-09-03 06:36:38

标签: sql ms-access ms-access-2007

我有4个课程和两个不同部门的学生的桌子(数学101,数学102,英语201,英语202)。我想选择数学101和英语201的学生,如果他们已经有,而英语202,如果他们已经有,或两者都有,如果他们两个都有。

<小时/> 编辑:

StudentID | Dept | CrsNum
 12345      MS     101
 99999      MS     102
 10000      EH     201
 56789      EH     201
 12345      EH     201
 12345      EH     202

理想情况下,查询结果会向学生12345显示他所经历的所有课程,因为他是唯一同时参加过MS 101和两门EH课程的人。

3 个答案:

答案 0 :(得分:1)

SELECT S1.StudentID
  FROM Students AS S1 JOIN (SELECT S3.StudentID
                              FROM Students AS S3
                             WHERE S3.Dept = 'MS'
                               AND S3.CrsNum = 101) AS S2
       ON S1.StudentID = S2.StudentID
 WHERE S1.Dept = 'EH'
   AND S1.CrsNum IN (201, 202);

或者,如果需要所有信息(如评论中所示),请将其用作选择相关学生ID的子查询:

SELECT * FROM Students
 WHERE StudentID IN
            (SELECT S1.StudentID
               FROM Students AS S1 JOIN (SELECT S3.StudentID
                                           FROM Students AS S3
                                          WHERE S3.Dept = 'MS'
                                            AND S3.CrsNum = 101) AS S2
                    ON S1.StudentID = S2.StudentID
              WHERE S1.Dept = 'EH'
                AND S1.CrsNum IN (201, 202));

答案 1 :(得分:1)

一个简单的子查询可以:

select StudentID from table where 
(Dept = "MS" and CrsNum = 101) and 
StudentID in ( select StudentID from table where
             ( (Dept = "EH" and CrsNum = 201) or
               (Dept = "EH" and CrsNum = 202) ) )

答案 2 :(得分:1)

尝试类似:

select StudentID, Dept, CrsNum
from StudentCourse SC
where CrsNum in (101, 201, 202) and
exists 
(select null
 from StudentCourse SC1
 where SC.StudentID = SC1.StudentID and
       sc1.CrsNum = 101) and
exists 
(select null
 from StudentCourse SC2
 where SC.StudentID = SC2.StudentID and
       sc1.CrsNum in (201,202))

或者,您应该能够在没有任何带有查询的子查询的情况下执行此操作:

select StudentID, 
       Sum(case when CrsNum = 101 then 1 else 0) InCrs101,
       Sum(case when CrsNum = 201 then 1 else 0) InCrs201,
       Sum(case when CrsNum = 202 then 1 else 0) InCrs202
from StudentCourse SC
where CrsNum in (101, 201, 202)
group by StudentID
having Sum(case when CrsNum = 101 then 1 else 0) >= 1 and
       (Sum(case when CrsNum = 201 then 1 else 0) >= 1 or
        Sum(case when CrsNum = 202 then 1 else 0) >= 1)