我有一个存储过程,它带有1个参数,一个ID号(systudentid)。
该程序返回3行:学生的学术辅导员(AC),财务顾问(FC)和招生顾问(EC)以及相关的联系信息; 3个不同的人。
某些学生的AC和FC是同一个人,但查询仍将返回3行。
AdvisorType|AdvisorLastName|AdvisorFirstName|(other data)|systaffID
AC DOE JOHN ..... 12345
AC DOE JOHN ..... 12345
EC SMITH JANE ..... 45678
在我的代码中,我可以插入逻辑(以及如何,我是sql的新手),以便当传递给过程的systudentid识别出具有AC和FC的同一个人的学生时,它将显示这样的结果。
顾问类型更改为“SSA”,只返回双重辅导员的一条记录。
AdvisorType|AdvisorLastName|AdvisorFirstName|(other data)|SystaffID
SSA DOE JOHN ...... 12345
EC SMITH JANE ...... 45678
这是我的选择声明:
SELECT
SyStaffGroup.Descrip AS AdvisorType
,SyStaff.LastName AS AdvisorLastName
,SyStaff.FirstName AS AdvisorFirstName
,SyStaff.Phone AS AdvisorPhone
,SyStaff.Ext AS AdvisorExtention
,SyStaff.eMail AS AdvisorEMail
,SyStaff.SyStaffID AS SyStaffID
FROM SyStaff (NOLOCK)
JOIN SyAdvisorByEnroll (NOLOCK)
ON SyAdvisorByEnroll.SyStaffID = SyStaff.SyStaffID
JOIN SyStaffGroup (NOLOCK)
ON SyStaffGroup.SyStaffGroupID = SyAdvisorByEnroll.SyStaffGroupID
JOIN AdEnroll (NOLOCK)
ON AdEnroll.AdEnrollID = SyAdvisorByEnroll.AdEnrollID
JOIN SyStudent (NOLOCK)
ON AdEnroll.SyStudentID = SyStudent.SyStudentId
WHERE
SyStaff.Active = 1
--AND
--syadvisorbyenroll.adenrollid = (
--SELECT adenrollid from dbo.fn_student_enrollment_activeenrollmentlist (@systudentid)
--)
AND adEnroll.adEnrollID IN (
SELECT adEnrollID FROM dbo.fn_Student_Enrollment_ActiveEnrollmentList(@SyStudentID)
)
AND SyAdvisorByEnroll.AdvisorModule IN ('AD','FA')
AND SyStaffGroup.Descrip IN ('AC - Academic Counselor', 'FC - Finance Counselors', 'EC - Adm. Counselor With Reg')
UNION
SELECT DISTINCT
'Admissions Counselor' AS AdvisorType
,SyStaff.LastName AS AdvisorLastName
,SyStaff.FirstName AS AdvisorFirstName
,SyStaff.Phone AS AdvisorPhone
,SyStaff.Ext AS AdvisorExtention
,SyStaff.eMail AS AdvisorEMail
,SyStaff.SyStaffID AS SyStaffID
FROM systudent
INNER JOIN AmRep ON SyStudent.AMREpID = AmREp.AMREpid
INNER JOIN SyStaff ON SyStaff.SyStaffID = AmRep.AmRepID
WHERE Systudent.SYStudentid = @systudentid
我可以尝试或谷歌的任何提示或建议的方法(我已经尝试过搜索,但如果我知道要查找什么,结果会更有用)将非常感激。
答案 0 :(得分:0)
您可以添加嵌套子查询以指示哪些学生具有填充多个职位的相同顾问,并相应地调整类型选择。以下是您上述查询的更改部分:
SELECT
CASE WHEN (mutiples.SyStaffID IS NOT NULL) THEN 'SSA'
ELSE SyStaffGroup.Descrip END AS AdvisorType
-- other columns omitted
FROM SyStaff (NOLOCK)
JOIN SyAdvisorByEnroll (NOLOCK)
ON SyAdvisorByEnroll.SyStaffID = SyStaff.SyStaffID
LEFT JOIN (
SELECT SyStaffID,AdEnrollID
FROM SyAdvisorByEnroll
GROUP BY SyStaffID,AdEnrollID
HAVING COUNT(DISTINCT SyStaffGroupID) > 1
) multiples
ON multiples.SyStaffID = SyAdvisorByEnroll.SyStaffID
AND multiples.AdEnrollID = SyAdvisorByEnroll.AdEnrollID
-- rest of query omitted
这可能有两两个错误,因为您没有包含表架构。嵌套子查询“倍数”包含顾问程序在多个组中的所有顾问/登记者对。如果嵌套子查询中存在匹配的条目,则保持联接对此并将最终类型选择调整为“SSA”。
一个重要的注意事项:如上所述,这将包括符合条件的顾问/登记者对的两个SSA行。但是,最终结果不会,因为您在此查询中使用了UNION,它会过滤掉重复项,即使它们仅出现在联合的一半中。如果将其更改为UNION ALL或完全取消UNION,则需要将DISTINCT添加到查询的顶部,如下所示:
SELECT DISTINCT CASE WHEN (mutiples.SyStaffID IS NOT NULL) ...