1

我正在尝试列出在秋季学期至少参加一门课程或在春季学期至少参加一门课程的学生,但不能同时参加这两个课程。我试图从不同的角度来解决这个问题,但到目前为止我还没有成功。我觉得完成此解决方案的代码如下。任何帮助表示赞赏!

SELECT enrolled.StudentID, student.LastName, student.FirstName
   , enrolled.courseID, enrolled.Quarter  
FROM enrolled 
INNER JOIN student ON enrolled.studentID = student.SID
GROUP BY enrolled.StudentID, student.LastName, student.FirstName
   , enrolled.courseID, enrolled.Quarter
HAVING (count(distinct enrolled.Quarter) = 1)
4

4 回答 4

0

您可以使用以下内容:

 SELECT 
   enrolled.StudentID, student.LastName, 
   student.FirstName, enrolled.courseID, enrolled.Quarter  
 FROM enrolled
 where StudentID in ( 
     SELECT StudentID 
     FROM enrolled where quarter in ( 'fall', 'spring' )
     group by StudentID
     having count(*) = 1 
   )      
于 2013-04-23T22:30:17.393 回答
0

对不起,在我的手机上,所以不会是一个完整的答案。

我会尝试

Select [what you want]
From students as s
Outer apply
(
Select distinct sid 
From enrolled as e
Where e.sid =s.sid
And quorter = 1
) as q1
Outer apply
(
 Select distinct sid 
From enrolled as e
Where e.sid =s.sid
And quorter = 2
) as q2
Where
((  q1.sid  is null and q2.sid is not null)
Or 
( q1.sid is not null and q2.sid is null))
And (q1.sid is not null and q2.sid is not null)
于 2013-04-23T22:31:01.233 回答
0

我会做一个联合查询。

select yourfields
from enrolled
where studentid in
(select studentid
from enrolled 
where quarter = 'fall'
minus
select studentid
from enrolled 
where quarter = 'spring')

union all
select yourfields
from enrolled
where studentid in
(select studentid
from enrolled 
where quarter = 'spring'
minus
select studentid
from enrolled 
where quarter = 'fall')

不完全确定 MySQL 是否支持关键字减号。有些分贝会,有些不会。如果不是,它可能支持关键字 except。

于 2013-04-23T22:34:26.847 回答
0

Stouny 的评论是正确的,从工作中删除quartergroup by使用聚合器select

SELECT enrolled.StudentID, student.LastName, student.FirstName, enrolled.courseID, max(enrolled.Quarter) as quarter
FROM enrolled 
INNER JOIN student ON enrolled.studentID = student.SID
GROUP BY enrolled.StudentID, student.LastName, student.FirstName, enrolled.courseID
HAVING count(*) = 1

如果您有很多季度要检查,另一种方法将无法很好地扩展,但适用于 2:

SELECT enrolled.StudentID, student.LastName, student.FirstName, coalesce(spring.courseID, fall.courseID), coaleasce(spring.Quarter, fall.quarter)  
FROM students
LEFT OUTER JOIN enrolled as spring ON spring.studentId = students.sid and spring.quarter = 'spring'
LEFT OUTER JOIN enrolled as fall ON fall.studentId = students.sid and fall.quarter = 'fall'
WHERE (spring.courseID != NULL and fall.courseID = NULL) OR (spring.courseID ! NULL and fall.courseID != NULL)
于 2013-04-23T22:43:02.567 回答