SQL Server 2016:如何判断讲师等级是否满足课程授课要求
Solution for Matching Instructors to Qualifying Dive Training Courses
Let's break this down to solve your problem clearly—since your character-based level codes can't be directly compared numerically, we'll leverage the ITITLE table's TNUM to map those codes to meaningful rank values.
Step 1: Clarify Table Relationships
CLASS.IREQlinks toITITLE.TABRto get the minimum required rank number (TNUM) for the courseINST.INSTYPElinks toITITLE.TABRto get the instructor's current rank number (TNUM)- The core check: an instructor is qualified if their
TNUMis greater than or equal to the course's requiredTNUM
Step 2: Full Working SQL Query
This query returns all July-starting, SD-prefixed courses paired with instructors who have a high enough rank to teach them:
SELECT c.CNUMBER AS Course_Number, c.CNAME AS Course_Name, c.STARTDATE AS Start_Date, i.INSTID AS Instructor_ID, i.NAME AS Instructor_Name, t_inst.TITLE AS Instructor_Rank, t_req.TITLE AS Required_Course_Rank FROM CLASS c -- Join to fetch the course's required rank details INNER JOIN ITITLE t_req ON c.IREQ = t_req.TABR -- Join to connect instructors and their rank details INNER JOIN INST i INNER JOIN ITITLE t_inst ON i.INSTYPE = t_inst.TABR -- Critical condition: instructor's rank meets or exceeds course requirements WHERE t_inst.TNUM >= t_req.TNUM -- Filter for your target courses AND c.CNUMBER LIKE 'SD____' AND MONTH(c.STARTDATE) = 7 -- Optional: Sort results for better readability ORDER BY c.CNUMBER, t_inst.TNUM DESC;
Key Adjustments & Notes
- If you want to see all qualifying courses even if no instructor is available to teach them, swap the
INNER JOINonINSTwith aLEFT JOIN - The
LIKE 'SD____'assumes your course numbers are 6 characters long (SD + 4 additional characters)—adjust the number of underscores if your course number format differs - Using
ITITLE.TNUMavoids the pitfalls of comparing character codes directly (e.g., a code like "B1" might come before "A2" lexicographically but have a lower actual rank)
Why Your Previous Subquery May Have Failed
Subqueries can get tangled here if you don't properly link the ITITLE table to both CLASS and INST in the same context. Explicit joins keep the logic transparent, making it easier to debug mismatched relationships or filter conditions.
内容的提问来源于stack exchange,提问作者Sean D.F.
相关产品推荐
相关产品推荐

