tcode
tcode

Reputation: 5105

Match All Records

I am having difficulty with writing an SQL query for my application. Below shows a screenshot of some of the tables in my database.

enter image description here enter image description here

Please let me explain how a section of my application works, and then I can show you the problem I am having with my SQL query.

A User can create an application form on my system (dbo.Form). An application form consists of several sections, one of those sections is Employment History (dbo.FormEmployment). An employment record includes details like employer name, start date etc, but also a gradeID. A User can add one or more employment records to the table dbo.FormEmployment.

A system administrator can add a Shift (dbo.Shift) to the system, and also then assign Grades to a Shift. These Grades are recorded in the dbo.ShiftGrade table. A Shift can be assigned 1 or more Grades, i.e. it could be assigned 1,2,3,4 or 5 Grades.

When the system administrator has added the Shift and Shift Grades, I then want to perform an SQL query to return a list of Users whose Grades match that of the Grades assigned to a Shift (remember the User adds their Grade when they add an employment record).

I have written the following SQL query which works, however, the issue with this query is that it returns a list of Users, that have any Grade that matches that of the Grades assigned to a Shift.

SELECT   u.userID, u.userTypeID, u.firstName, u.lastName, u.email, u.password, 
u.contactNumber, u.organisationID, u.emailVerificationCode, u.mobileVerificationCode, 
u.userStatusID, u.AddedBy, u.AddedDate, u.ModifiedBy, u.ModifiedDate
FROM     [User] u
--Check Grades Match
WHERE    u.userID IN
     (
     SELECT f.locumID
     FROM   dbo.Form f, dbo.FormEmployment emp
     WHERE  f.formID = emp.formID
     AND    emp.statusID = 101
     AND    emp.workYN = 1
     AND    emp.gradeID IN (
             select gradeID from dbo.ShiftGrade where shiftID = @p0
             )
     )

You can see I am using the IN statement to do this. However, I only want to return a list of Users who can match exactly the same Grades that have been assigned to a Shift. Therefore, if a Shift has been assigned 3 Grades, then I want a List of Users who also have the exact same three Grades to be returned.

I apologise for the lengthy post, I just thought it would be better explained this way. Any feedback or help with this would be greatly appreciated.

Upvotes: 2

Views: 152

Answers (1)

abatishchev
abatishchev

Reputation: 100258

select u.*
from dbo.Users u
join dbo.Form f on u.? = f.formId
join dbo.FormEmployment fe on fe.formId = f.formId
join dbo.Grade g on g.gradeId =  fe.gradeId
join dbo.ShiftGrade shg on shg.gradeId =g.gradeId
join dbo.Shift sh on sh.shiftId = shg.shiftId
where
    sh.shiftId = -- recently added shift id
and g.gradeId == -- recently added grade id

Upvotes: 1

Related Questions