Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
velnias2010
Posting Yak Master
125 Posts |
Posted - 2011-06-16 : 05:21:46
|
| I have the following query which works fineSELECT r.userId, r.programmeId, u.email, u.firstName, u.lastName, u.profileId, tblProgrammes.name, u.storeId, r.dateEnded AS lastPass, r.dateExpiredFROM tblUserRepeatHistory AS r INNER JOIN tblUsers AS u ON r.userId = u.id INNER JOIN tblProgrammes ON r.programmeId = tblProgrammes.idWHERE (u.storeId = @storeId) AND (r.userId = @userId)GROUP BY r.userId, r.programmeId, u.email, u.firstName, u.lastName, u.profileId, tblProgrammes.name, u.storeId, r.dateEnded, r.dateExpiredHAVING (DATEDIFF(D, MAX(r.dateExpired), GETDATE() + 31) >= 0)ORDER BY tblProgrammes.nameIm basically checking an Historical table and looking if a user is due to repeat an exam again and this works fine. I basically get a record back as follows if the the above is true10 25 staff-member jamie1 2 Deli Food Service 3 5 17/05/2010 10:14:21 15/07/2011 10:14:21Now if I get a hit back I want to check another table and make sure that he hasnt currently doing this exam.This query is as followsSELECT TOP (1) r.id, p.maxStepsFROM tblUserQuestionnaireHistory AS r INNER JOIN tblProgrammes AS p ON r.programmeId = p.id AND r.stepId = p.maxStepsWHERE (r.userId = @UserId) AND (r.programmeId = @ProgrammeId) AND (r.success = 1)ORDER BY r.id DESCSo basically in the second query the parameters @ProgrammeId and @UserId should come from the first query. But since this is a query where I want the get the people who haven't done the test. I want the second query to be WHERE NOT EXISTS. I.e. If I get a hit back in the second query then the user is fine, but if I get nothing back then I want the joined query basically to return the same data as the first query10 25 staff-member jamie1 2 Deli Food Service 3 5 17/05/2010 10:14:21 15/07/2011 10:14:21 |
|
|
velnias2010
Posting Yak Master
125 Posts |
Posted - 2011-06-16 : 06:34:57
|
| Maybe to make this query a bit simpler lets say I haveSELECT r.userId, r.programmeId, u.email, u.firstNameFROM tblUserRepeatHistoryFor Each Record Returned I would then would want to join that withSELECT TOP (1) r.idFROM tblUserQuestionnaireHistory AS r WHERE (r.userId = @UserId) AND (r.programmeId = @ProgrammeId) AND (r.success = 1) AND r.stepId = 9How could I join the two queries as suchSELECT r.userId, r.programmeId, u.email, u.firstNameFROM tblUserRepeatHistory (SELECT WHERE NOT EXISTS TOP (1) r.idFROM tblUserQuestionnaireHistory AS r WHERE (r.userId = @UserId) AND (r.programmeId = @ProgrammeId) AND (r.success = 1) AND r.stepId = 9)Where @ProgrammeId and @userId would come from the first select |
 |
|
|
|
|
|
|
|