我正在尝试查看一个查看单个表的查询,以查看学生是否在一个名为CMHT的团队和一个军医团队中 - 如果他们是我不想看到结果。
我只想看到记录,如果他们只是在CMHT或军医,而不是两者。
正确的方向是使用子查询来过滤掉它吗?我已经对NOT IN进行了搜索,但你怎么能看到它是否超过2支球队?
Student Team ref
1 CMHT 1
1 Medic 2
2 Medic 3 this would be in the result
3 CMHT 5 this would be in the result
到目前为止,我已经完成了以下代码,我是否需要使用子查询或进行自我连接并以此方式过滤?
SELECT Table1.Student, Table1.Team, Table1.refnumber
FROM Table1
WHERE (((Table1.Team) In ('Medics','CMHT'))
答案 0 :(得分:2)
这是Mark Byers用HAVING子句而不是子查询的答案:
SELECT Student, Team, ref
FROM Table1
GROUP BY Student
HAVING COUNT(Student) = 1
答案 1 :(得分:1)
SELECT *
FROM students
WHERE NOT EXISTS
(
SELECT NULL
FROM students si
WHERE si.student = s.student
AND si.team = 'CMHT'
)
OR NOT EXISTS
(
SELECT NULL
FROM students si
WHERE si.student = s.student
AND si.team = 'Medic'
)
答案 2 :(得分:1)
SELECT a.*
FROM Table1 a
INNER JOIN
( SELECT Student, COUNT(*) FROM Table1
GROUP BY Student
HAVING COUNT(*) = 1)b
ON (a.Student = b.Student)
答案 3 :(得分:1)
你怎么能看到它是否在2个或更多团队中检查?
您可以计算每位学生的团队数量,然后只过滤您想要查看的人数:
SELECT student FROM
(
SELECT student, COUNT(*) AS cnt
FROM Table1
GROUP BY student
) T1
WHERE cnt = 1
答案 4 :(得分:1)
您可以使用外部联接
select COALESCE(t1.Student, t2.Student) as Student,
COALESCE(t1.Team, t2.Team) as Team,
COALESCE(t1.ref, t2.ref) as ref
from
(select * from Student where Team = 'CMHT') t1
outer join
(select * from Student where Team = 'Medic') t2
on t1.Student = t2.Student
where
t1.Student is null or
t2.Student is null;