tags:

views:

75

answers:

5
+4  Q: 

Help with query

I'm trying to make a query that looks at a single table to see if a student is in a team called CMHT and in a medic team - if they are I don't want to see the result.

I only want see the record if they're only in CMHT or medic, not both.

Would the right direction be using sub query to filter it out? I've done a search on NOT IN but how could you get to see check if its in more then 2 teams are not?

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

So far I've done the following code would I need use a sub query or do a self join and filter it that way?

SELECT Table1.Student, Table1.Team, Table1.refnumber
  FROM Table1
 WHERE (((Table1.Team) In ('Medics','CMHT')) 

+1  A: 
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'
        )
Quassnoi
+1  A: 
SELECT a.*
FROM Table1 a
INNER JOIN 
( SELECT Student, COUNT(*) FROM Table1 
GROUP BY Student 
HAVING COUNT(*) = 1)b
ON (a.Student = b.Student)
a1ex07
+1  A: 

how could you get to see check if its in 2 or more teams?

You can count the number of teams per student and then filter only those you want to see:

SELECT student FROM
(
    SELECT student, COUNT(*) AS cnt
    FROM Table1
    GROUP BY student
) T1
WHERE cnt = 1
Mark Byers
+1  A: 

You can do it with outer join

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;
Fede
`MySQL` does not support `FULL OUTER JOIN`.
Quassnoi
sorry, didn't know. saw the question was also tagged with tsql, and thought that a SqlServer syntax and behavior for outer joins would be valid.
Fede
+2  A: 

This is Mark Byers's answer with a HAVING clause instead of a subquery:

SELECT Student, Team, ref
FROM Table1
GROUP BY Student
HAVING COUNT(Student) = 1
Marcus Adams
Hey Thanks :) dint think to do a count.. :)
o ps thanks for everyone help :) - on another subject how does an outer join work??
@hdoe123: Another subject = another question.
Mark Byers
@Marcus Adams: +1 Nice improvement to my answer! :)
Mark Byers