Link to home
Start Free TrialLog in
Avatar of Kristen Jones
Kristen JonesFlag for United States of America

asked on

MS SQL JOIN Syntax

I need help with an SQL Join/results

I have two tables SCHOOLS and STUDENTS  They both have a SCHOOLID that can be joined.  What I need to see are ALL of the SCHOOLS and fields from the SCHOOLS table and  a virtual field telling me if there are ANY STUDENTS that have that SCHOOLID.

Example:

SCHOOLS
   SchoolID
   School
   Active

STUDENTS
   name
   SchoolID

 RESULT Table:
SchoolID     Active     Used (yes or No)  

So the virtual field USED is telling me if there are ANY schools that are in the STUDENTS table.  

Then I want to make another query that I can add a where clause to the SchoolID  So SAME result be asking "Does SchoolID have any students from the STUDENTS table that have that SchoolID"  Then it would list that school (ONE RECORD)  SchoolID, School, Active, Used
Avatar of Norie
Norie

For the first query try this.

SELECT Schools.SchoolID, Schools.School, Schools.Active, IIF(Students.SchoolID IS NULL, 'No', 'Yes') AS Used
FROM Schools
LEFT JOIN Students ON Schools.SchoolID = Students.SchoolID;
Avatar of Kristen Jones

ASKER

It is a 2008 SQL server so IIF is not a Function  I just tried a direct replacement using CASE and it has a lot of other Syntax errors
This worked (I had a typo on the field name)  But it appears to query all of the students rather than just the SCHOOLS


CASE WHEN Students.SchoolID IS NULL THEN 'Yes' ELSE 'No' end  
FROM Schools
LEFT JOIN Students ON Schools.SchoolID = Students.SchoolID;
Looking at this again the results are not right.  I tried an outer join and it still tries to do a one to many.  I just want each school (record) to look through all of the STUDENTS (SchoolD) for it..  if ANY of the STUDENT table has a match .... And there could be 1000's of matches, I just need to know if it was ever used then the single school record say 'Yes' OR 'No' then move to the next record in the SCHOOL table.
ASKER CERTIFIED SOLUTION
Avatar of Norie
Norie

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It is grabbing and returning all of the Students 1000's  there are only about 40 schools so I am expecting only the Schools  and either Yes or no on the USED
That worked .. thanks!