我正在尝试列出在秋季季度至少注册一门课程或在春季开设至少一门课程的学生,但不是两者。我试图从不同角度去做这件事,但到目前为止我还没有成功。我认为完成此解决方案的代码如下。任何帮助表示赞赏!
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)
答案 0 :(得分: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
)
答案 1 :(得分: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)
答案 2 :(得分: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是否支持关键字minus。有些db有,有些则没有。如果没有,它可能支持关键字除外。
答案 3 :(得分:0)
Stouny的评论是正确的,从quarter
中移除group 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)