SQL查询以获取已注册英语或乌尔都语课程但未同时注册这两门课程的学生
查询应返回Naveed Rizwan Fayaz和Ahmed姓名 SQL查询,适用于已注册英语或乌尔都语课程但未同时注册英语或乌尔都语课程的学生SQL查询以获取已注册英语或乌尔都语课程但未同时注册这两门课程的学生,sql,sql-server,database,Sql,Sql Server,Database,查询应返回Naveed Rizwan Fayaz和Ahmed姓名 SQL查询,适用于已注册英语或乌尔都语课程但未同时注册英语或乌尔都语课程的学生 declare @Student table(sid int identity(1, 1), sname varchar(250)) declare @Course table(cid int identity(1, 1), cname varchar(250)) declare @StudentCourse table(cid int, sid i
declare @Student table(sid int identity(1, 1), sname varchar(250))
declare @Course table(cid int identity(1, 1), cname varchar(250))
declare @StudentCourse table(cid int, sid int)
insert into @Student(sname)
select 'Mehboob' union all --1
select 'Rahim' union all -- 2
select 'Naveed' union all --3
select 'Rizwan' union all --4
select 'Fayaz' union all --5
select 'Ahmed' -- 6
insert into @Course(cname)
select 'English' union all
select 'Urdu'
insert into @StudentCourse(sid ,cid)
select 1,1 union all
select 2,1 union all
select 3,1 union all
select 4,1 union all
select 5,2 union all
select 6,2 union all
select 1,2 union all
select 2,2
我一直在练习,最后我通过这个问题做到了,你们还有其他想法吗
select
s.*, count(1) as TotalEnrolledCourses
from
@Student s
inner join
@StudentCourse sc on s.sid = sc.sid
where
sc.cid in (1,2)
group by
s.sid, sname
having
TotalEnrolledCourses = 1
这是解决问题的另一种方法:
SELECT
s.sid,
s.sname
FROM @StudentCourse sc
INNER JOIN @Student s
ON s.sid = sc.sid
WHERE
sc.cid IN(1, 2)
GROUP BY
s.sid, s.sname
HAVING
(
SUM(CASE WHEN sc.cid = 1 THEN 1 ELSE 0 END) +
SUM(CASE WHEN sc.cid = 2 THEN 1 ELSE 0 END)
) = 1
从这里你可以获得一个注册课程的学生的完整信息,即姓名和ID等
SELECT s.*
FROM Student s
INNER JOIN (select sid, max(cid)
from StudentCourse
group by sid
having count(*)=1
) sc ON s.sid=sc.sid
那么预期的结果是什么呢?查询应该返回Naveed Rizwan Fayaz和Ahmed Name。这应该是
具有count(1)=1
。如果我错了,请纠正我,但是(1,2)中的条件sc.cid不是XOR…意味着它意味着课程1或课程2?
SELECT s.*
FROM Student s
INNER JOIN (select sid, max(cid)
from StudentCourse
group by sid
having count(*)=1
) sc ON s.sid=sc.sid